﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using System.IO;
using System.Drawing.Imaging;
using System.Text.RegularExpressions;
using System.Threading;
using System.Collections.Specialized;
using System.Runtime.InteropServices;
using System.Text;

namespace WChat {
    /// <summary>
    /// 消息聊天框
    /// </summary>
    /// 

    #region 截图所需数据
    [Flags]
    public enum KeyModifiers {
        None = 0,
        Alt = 1,
        Ctrl = 2,
        Shift = 4,
        WindowsKey = 8
    }

    #endregion

    [System.Runtime.InteropServices.ComVisible(true)]
    public partial class WChatBox : UserControl {
        SqlHandle sql = new SqlHandle();
        SqlTest ss = new SqlTest();
        WXMsg Quan_msg = new WXMsg();//放到全局，配合线程试用
        public event FriendInfoViewEventHandler FriendInfoView;
        private string _fil_base64 = "data:img/jpg;base64,";
        private string _Voi_base64 = "data:img/jpg;base64,";
        private string _gro_base64 = "data:img/jpg;base64,";
        private string _friend_base64 = "data:img/jpg;base64,";
        private string _me_base64 = "data:img/jpg;base64,";
        private string _locicon_base64 = "data:img/jpg;base64,";
        private string sendpic_base64 = "data:img/jpg;base64,";
        private string recpic_base64 = "data:img/jpg;base64,";
        private bool HaveScreenShot = false;
        private delegate void myInvoke();
        private string path = WChat.path.paths;
        private List<WXMsg> piczoom = new List<WXMsg>();
        private string Admin;
        //聊天好友
        private WXUser _friendUser;
        public WXUser FriendUser {
            get {
                return _friendUser;
            }
            set {
                if (value != _friendUser) {
                    if (_friendUser != null) {
                        _friendUser.MsgRecved -= new MsgRecvedEventHandler(_friendUser_MsgRecved);
                        _friendUser.MsgSent -= new MsgSentEventHandler(_friendUser_MsgSent);                        
                    }
                    _friendUser = value;
                    if (_friendUser != null) {
                      
                        _friendUser.MsgRecved += new MsgRecvedEventHandler(_friendUser_MsgRecved);
                        _friendUser.MsgSent += new MsgSentEventHandler(_friendUser_MsgSent);

                        if (_friendUser.Icon == null)  //头像信息
                        {
                            using (MemoryStream ms = new MemoryStream()) {
                                Bitmap backImage = new Bitmap(this.GetType(), "headpic.jpg");
                                Bitmap b = new Bitmap(backImage);
                                b.Save(ms, ImageFormat.Png);
                                _me_base64 = "data:img/jpg;base64," + Convert.ToBase64String(ms.ToArray());
                            }
                        }
                        else {    //头像信息
                            using (MemoryStream ms = new MemoryStream()) {
                                _friendUser.Icon.Save(ms, ImageFormat.Png);
                                _friend_base64 = "data:img/jpg;base64," + Convert.ToBase64String(ms.ToArray());
                            }
                        }
                        webBrowser1.DocumentText = _totalHtml = "";
                        lblInfo.Text = "与 " + _friendUser.ShowName + " 聊天中";
                        lblInfo.Location = new Point((plTop.Width - lblInfo.Width) / 2, lblInfo.Location.Y);
                        ShowFirstMsg();
                        IEnumerable<KeyValuePair<DateTime, WXMsg>> dic = _friendUser.RecvedMsg.Concat(_friendUser.SentMsg);
                        dic = dic.OrderBy(i => i.Key);
                        foreach (KeyValuePair<DateTime, WXMsg> p in dic)  //恢复聊天记录
                        {
                            p.Value.Readed = true;
                        }                       
                    }             
                }
            }          
        }
        //自己
        private WXUser _meUser;
        public WXUser MeUser {
            get {
                return _meUser;
            }
            set {
                _meUser = value;

                if (_meUser.Icon == null)  //头像信息
                {
                    using (MemoryStream ms = new MemoryStream()) {
                        Bitmap backImage = new Bitmap(this.GetType(), "headpic.jpg");
                        Bitmap b = new Bitmap(backImage);
                        b.Save(ms, ImageFormat.Png);
                        _me_base64 = "data:img/jpg;base64," + Convert.ToBase64String(ms.ToArray());
                    }
                }
                else {
                    using (MemoryStream ms = new MemoryStream()) {
                        _meUser.Icon.Save(ms, ImageFormat.Png);
                        _me_base64 = "data:img/jpg;base64," + Convert.ToBase64String(ms.ToArray());
                    }
                }
            }
        }

        public FormWindowState WindowState { get; private set; }
    
       public string ShowSend(WXMsg msg) {
            string _msg = "";
            switch (msg.Type) {
            case "1":
            _msg= showsendmsg(msg);
            break;
            case "3":
            _msg = showsendpic(msg);
            break;
            case"42":
            _msg = showsendcard(msg);   //发送名片
            break;
            case "34":
            _msg = showsendvoice(msg); //语音消息
            break;
            case "47":
            _msg = showsendmsg(msg);  //不支持的表情
            break;
            case "99":
            _msg = showlocpic(msg);
            break;
            case "49":
                if (msg.FileName == "微信转账") {
                _msg = showreceivemsg(msg);
                }
                else if (msg.TxtUrl.Trim() == "" && msg.TxtUrl.Length == 0) { //文件
                _msg = showsendfilemsg(msg);
                }
                else {
                _msg = showsendurlmsg(msg);
                }
            break;
            case "10000":
                msg.Msg = "发出红包，请在手机上查看";
            _msg = showsendmsg(msg);
            break;
            default:
            _msg = showsendmsg(msg);
            break;
            }
            return _msg;
        } 

       public string ShowReceive(WXMsg msg) {
            string _msg = "";
            switch (msg.Type) {
            case "1":
                 _msg = showreceivemsg(msg);
            break;
            case "3":
                 _msg = showreceivepic(msg);
            break;
            case "34":
                 _msg = showreceivevoice(msg);     //接受语音
            break;
            case "42":
                 _msg = showreceivecard(msg);   //接受名片
            break;
            case "47":
                 _msg = showreceivemsg(msg);  
            break;
            case "37":
                 _msg = showreceiveverifymsg(msg);
            break;
            case "49":
                if (msg.FileName == "微信转账") {
                _msg = showreceivemsg(msg);
            } else if (msg.TxtUrl.Trim() == "" && msg.TxtUrl.Length == 0) { //文件
                _msg = showreceivefilemsg(msg);  //先屏蔽了，否则会卡死
            } else {                      
                _msg = showreceiveurlmsg(msg); //链接
            }
            break;
            case "10000":
            _msg = showreceivemsg(msg);
            break;
            default:
            _msg = showreceivemsg(msg);
            break;
            }
            return _msg;
        } 
        /// <summary>
        /// 构造方法
        /// </summary>
        public WChatBox() {
            InitializeComponent();
            webBrowser1.IsWebBrowserContextMenuEnabled = true;
            if (webBrowser1.Document != null) {
                webBrowser1.Document.InvokeScript("go");
            }
            this.webBrowser1.ObjectForScripting = this;
            webBrowser1.ScriptErrorsSuppressed = true;
            emojiPanel1.Epanel += EmojiPanel1_Epanel;
               
            #region 快捷回复                                                                            
            tbx_new_reply.LostFocus += Tbx_new_reply_LostFocus;
            tbx_new_reply.GotFocus += Tbx_new_reply_GotFocus;
            #endregion
        }

        private void Tbx_new_reply_GotFocus( object sender, EventArgs e ) {
            TextBox t = ((TextBox)sender);
            if (t.ForeColor == Color.Silver) {
                t.Text = "";
                t.ForeColor = Color.Black;
            }
        }

        private void Tbx_new_reply_LostFocus( object sender, EventArgs e ) {
            TextBox t = ((TextBox)sender);
            if (t.Text.Trim() == "") {
                t.ForeColor = Color.Silver;
                t.Text = "请输入内容";
            }
        }

        private void EmojiPanel1_Epanel(string msg) {
            richTextBox1.AppendText(msg);
            richTextBox1.Focus();
        }

        /// <summary>
        /// 加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        [System.Runtime.InteropServices.ComVisibleAttribute(true)]
        /// <summary>
        /// 发送消息完成
        /// </summary>
        /// <param name="msg"></param>
        void _friendUser_MsgSent(WXMsg msg) {
            piczoom.Add(msg);
            if (msg.Type == "3") {
                ShowSendPIC(msg);
                //Thread pic_dowen = new Thread(_friendUser.SavePic);  //在这里提前保存图片，后面在点开时就会快点了
                //pic_dowen.Start();
            }
            else if (msg.Type == "1") {
                ShowSendMsg(msg);
            } else if (msg.Type == "34") {
                ShowSendVoice( msg); //显示发送语音
            }
            else if (msg.Type == "42") {
                ShowSendCard(msg);   //显示发送名片
            }
            else if (msg.Type == "99") {
                ShowLocPIC(msg);
            }
            else if (msg.Type == "49") {  //文件或链接
                if (msg.FileName == "微信转账") {
                    ShowSendMsg(msg);
                }
                else if (msg.TxtUrl == "") {
                    ShowSendfileMsg(msg);   //文件
                }
                else {
                    ShowSendUrlMsg(msg);
                }
            }
            else if (msg.Type == "47") {  //不支持的表情
                ShowSendMsg(msg);
            }else if (msg.Type == "10000") {
               // msg.Msg = "发出红包，请在手机上查看";
                ShowSendMsg(msg);
            }else {
                ShowSendMsg(msg);
            }
        }

        /// <summary>
        /// 收到新消息
        /// </summary>
        /// <param name="msg"></param>
        void _friendUser_MsgRecved(WXMsg msg) {
            piczoom.Add(msg);
            if (msg.Type == "3") {
                ShowReceivePIC(msg);
            }
            else if (msg.Type == "42") {
                ShowReceiveCard(msg);
            }
            else if (msg.Type == "49") {    //文件或者链接
                if (msg.FileName == "微信转账") {
                    ShowReceiveMsg(msg);
                }else if (msg.TxtUrl == "") { //文件
                    ShowReceiveFileMsg(msg);
                } else {
                    ShowReceiveUrlMsg(msg);
                }
            }
            else if (msg.Type == "1") {
                ShowReceiveMsg(msg);
            }
            else if (msg.Type == "0") {
                ShowReceiveMsg(msg);
            }
            else if (msg.Type == "34") {  //语音消息
                ShowReceiveVoice(msg);
            }
            else if (msg.Type == "47") {  //不支持的表情
                ShowReceiveMsg(msg);
            }else if (msg.Type == "37") {
                ShowReceiveVerifyMsg(msg);
            }else if (msg.Type == "10000") {
                ShowReceiveMsg(msg);
            }else {
                ShowReceiveMsg(msg);
            }
        }
      
        /// <summary>
        /// 大小改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void WChatBox_Resize(object sender, EventArgs e) {
            lblInfo.Location = new Point((plTop.Width - lblInfo.Width) / 2, lblInfo.Location.Y);
        }
        #region  消息框操作相关

        #region 显示发送消息
        /// <summary>
        /// UI界面显示发送消息  
        /// </summary>
        private void ShowSendMsg(WXMsg msg) {
            if (_meUser == null || _friendUser == null) {   return;   }
             
            string str = @"  <script type=""text/javascript"">
            window.location.hash = ""#ok"";</script>
             <div style=""clear:both; "">
             <li style=""  margin-bottom:13px;"" > <div style=""margin-top:6px;color:white; background:#808080; width:60px; border-radius:5px; position: absolute; right: 50%;text-align: center; "" class="" chat_nick"">" + msg.Time.ToString("T") + @"</div></li>  
            <div style=""width:40px; height:40px; border-radius:20px;border:2px solid #ADFF2F; overflow:hidden;float:right;"">
            <img  id = ""imgPre"" class=""chat_content_avatar"" src=""" + _me_base64 + @""" style="" height: 40px; width: 40px;"">
            </div>
            <div style=""float:right; top:5px; magin-right:-33px;  width:0; height:0; font-size:0; border:solid 8px;  margin-top:9px; border-color:#fff #fff #fff #32cd32; border-bottom-color:#fff;""></div>  
             <div  class= ""ss""  onclick=""go();"" style=""float:right; color:white; padding-top: 10px; padding-bottom: 10px; border-radius:5px; padding-left: 10px;padding-right: 10px; font-family:微软雅黑; height: auto; min-height:10px; width:auto; max-width:300px; background:#32cd32;""> <p class=""div"" style=""margin:0px auto;"">" + ConvertToGif(msg.Msg) + @"</p> </div>    
             </div> 
             <a id='ok'></a>";

            if (_totalHtml == "") {
                _totalHtml = _baseHtml;
            }
            webBrowser1.DocumentText = _totalHtml = _totalHtml.Replace("<a id='ok'></a>", "") + str;
        }

        /// <summary>
        /// 同步自己发送的图片
        /// </summary>
        private void ShowSendPIC(WXMsg msg) {
            if (_meUser == null || _friendUser == null) {
                return;
            }
            try {
                string picpath = path + "\\" + msg.MsgId + "small.jpg";
                if (File.Exists(picpath)) {
                    using (MemoryStream ms=new MemoryStream()) { 
                        Bitmap b = new Bitmap(picpath);
                        b.Save(ms, ImageFormat.Png);
                        sendpic_base64 = "data:img/jpg;base64," + Convert.ToBase64String(ms.ToArray());
                        b.Dispose();
                   }
               }
            }
            catch(Exception e) {
                WriteLog.Writelog("ShowSendPIC", e.ToString());
            }

            string str = @"<script type=""text/javascript"">window.location.hash = ""#ok"";</script> 
             <div style=""clear:both; "">
             <li style=""  margin-bottom:25px;"" > <div style=""color:white;margin-top:6px; background:#808080; width:60px; border-radius:5px; position: absolute; right: 50%;text-align: center; "" class="" chat_nick"">" + msg.Time.ToString("T") + @"</div></li>  
            <div style=""width:40px; height:40px; border-radius:20px;border:2px solid #ADFF2F; overflow:hidden;float:right;"">
                <img  id = ""imgPre"" class=""chat_content_avatar"" src=""" + _me_base64 + @""" style="" height: 40px; width: 40px;"">
            </div> 
            
             <div style=""float:right; top:5px; magin-right:-33px;  width:0; height:0; font-size:0; border:solid 8px;  margin-top:9px; border-color:#fff #fff #fff #32cd32; border-bottom-color:#fff;""></div>  
             <div  class= ""ss"" onclick=""go();"" style=""float:right; color:white; padding-top: 10px; padding-bottom: 10px; border-radius:5px; padding-left: 10px;padding-right: 10px; font-family:微软雅黑; height: auto; min-height:10px; width:auto; max-width:300px; background:#32cd32;""><img src=""" + sendpic_base64 + @""" /></div>     
             </div> 
            <a id='ok'></a>";

            if (_totalHtml == "") {
                _totalHtml = _baseHtml;
            }
            msg.Readed = true;
            webBrowser1.DocumentText = _totalHtml = _totalHtml.Replace("<a id='ok'></a>", "") + str;
        }
   
        /// <summary>
        /// 同步自己发送的语音消息
        /// </summary>
        private void ShowSendVoice( WXMsg msg ) {
            if (_meUser == null || _friendUser == null) {
                return;
            }
            try {
                using (MemoryStream ms = new MemoryStream()) {
                    Bitmap backImage = new Bitmap(this.GetType(), "voice_right.png");
                    Bitmap b = new Bitmap(backImage);
                    b.Save(ms, ImageFormat.Png);
                    _Voi_base64 = "data:img/jpg;base64," + Convert.ToBase64String(ms.ToArray());
                }
            }
            catch { }

            string str = @"<script type=""text/javascript"">window.location.hash = ""#ok"";</script> 
             <div style=""clear:both; "">
             <li style=""  margin-bottom:25px;"" > <div style=""color:white;margin-top:6px; background:#808080; width:60px; border-radius:5px; position: absolute; right: 50%;text-align: center; "" class="" chat_nick"">" + msg.Time.ToString("T") + @"</div></li>  
            <div style=""width:40px; height:40px; border-radius:20px;border:2px solid #ADFF2F; overflow:hidden;float:right;"">

                <img  id = ""imgPre"" class=""chat_content_avatar"" src=""" + _me_base64 + @""" style="" height: 40px; width: 40px;"">
            </div> 
            
             <div style=""float:right; top:5px; magin-right:-33px;  width:0; height:0; font-size:0; border:solid 8px;  margin-top:9px; border-color:#fff #fff #fff #32cd32; border-bottom-color:#fff;""></div>  
             <div  class= ""ss""  onclick=""go();"" style=""float:right; color:white; padding-top: 10px; padding-bottom: 5px; border-radius:5px;  font-family:微软雅黑; height:25px;  min-width:70px; max-width:300px; background:#32cd32;"">&nbsp &nbsp &nbsp &nbsp &nbsp <img src=""" + _Voi_base64 + @""" /></div>     
             </div> 
             <a id='ok'></a>";

            if (_totalHtml == "") {
                _totalHtml = _baseHtml;
            }
            msg.Readed = true;
            webBrowser1.DocumentText = _totalHtml = _totalHtml.Replace("<a id='ok'></a>", "") + str;
        }
        /// <summary>
        ///客户端发送图片
        /// </summary>
        private bool ShowLocPIC(WXMsg msg) {
            if (_meUser == null || _friendUser == null) {
                return false;
            }
            if (msg!= null)  //图片
              {
                using (MemoryStream ms = new MemoryStream()) {
                    string picpath = msg.FileName;
                    Bitmap b = new Bitmap(picpath);
                    b.Save(ms, ImageFormat.Png);
                    _locicon_base64 = "data:img/jpg;base64," + Convert.ToBase64String(ms.ToArray());
                    b.Dispose();
                }
            }
            string str = @"
             <script type=""text/javascript"">window.location.hash = ""#ok"";</script> 
             <div style=""clear:both; "">
             <li style=""  margin-bottom:25px;"" > <div style=""margin-top:6px;color:white; background:#808080; width:60px; border-radius:5px; position: absolute; right: 50%;text-align: center; "" class="" chat_nick"">" + msg.Time.ToString("T") + @"</div></li>  
             
            <div style=""width:40px; height:40px; border-radius:20px;border:2px solid #ADFF2F; overflow:hidden;float:right;"">
            <img  id = ""imgPre"" class=""chat_content_avatar"" src=""" + _me_base64 + @""" style="" height: 40px; width: 40px;"">  
            </div>
            <div style=""float:right; top:5px; magin-right:-45px;  width:0; height:0; font-size:0; border:solid 8px;  margin-top:9px; border-color:#fff #fff #fff #32cd32; border-bottom-color:#fff;""></div>  
            <div  class= ""ss""   onclick=""go();"" style=""float:right;color:white; padding-top: 10px; padding-bottom: 10px; border-radius:5px; padding-left: 10px;padding-right: 10px; font-family:微软雅黑; height: auto; min-height:10px; width:auto; max-width:300px; background:#32cd32;"">
            <img src=""" + _locicon_base64 + @""" width =""80px""  />
            </div>    
            </div> 
            <a id='ok'></a>";

            if (_totalHtml == "") {
                _totalHtml = _baseHtml;
            }
            msg.Readed = true;
            webBrowser1.DocumentText = _totalHtml = _totalHtml.Replace("<a id='ok'></a>", "") + str;
            return true;
        }
        /// <summary>
        ///客户端发送文件
        /// </summary>
        private void ShowSendfileMsg(WXMsg msg) {
            if (_meUser == null || _friendUser == null) {
                return;
            }
            using (MemoryStream ms = new MemoryStream()) {
                string picpath = msg.FileName;
                Bitmap backImage = new Bitmap(this.GetType(), "file.jpg");
                Bitmap b = new Bitmap(backImage);
                b.Save(ms, ImageFormat.Png);
                _fil_base64 = "data:img/jpg;base64," + Convert.ToBase64String(ms.ToArray());
            }
            string str = @"
              <script type=""text/javascript"">window.location.hash = ""#ok"";</script> 
             <div style=""clear:both; "">
             <li style=""  margin-bottom:25px;"" > <div style=""margin-top:6px;color:white; background:#808080; width:60px; border-radius:5px; position: absolute; right: 50%;text-align: center; "" class="" chat_nick"">" + msg.Time.ToString("T") + @"</div></li>  
            
           <div style=""width:40px; height:40px; border-radius:20px;border:2px solid #ADFF2F; overflow:hidden;float:right;"">
            <img  id = ""imgPre"" class=""chat_content_avatar"" src=""" + _me_base64 + @""" style="" height: 40px; width: 40px;"">  
            </div>
            <div style=""float:right; top:5px; magin-right:-33px;  width:0; height:0; font-size:0; border:solid 8px;  margin-top:9px; border-color:#fff #fff #fff #AAAAAA; border-bottom-color:#fff;""></div>  
               
             <div onclick=""go();""  class= ""ss"" style=""float:right; border-radius:5px;  margin-top:-13px; padding: 10px; font-family:微软雅黑; margin-left:0px;height: 80px; min-height:10px; width:auto; background:white; border:1px solid #AAAAAA;"">                    
                <div style=""width:140px;height:50px;text-overflow: ellipsis;overflow:hidden;margin-top:-15px; float:left;line-height:20px;"">
                    <p style=""text-overflow: ellipsis;overflow:hidden;font-size:14px;"">" + msg.Msg + @"</p>
                    <p style=""color:#AAAAAA;font-size:10px;"">" + msg.FileSize + "B" + @"</p>
                </div>
                <div style""width:140;float:right;"">
                    <img src="""+ _fil_base64 + @""" width =""30px""/>
                </div>
                <hr color=""#DDDDDD"" /> 
                <p style=""margin:0px;font-size:10px;color:#AAAAAA;"">环球云控</p>                          
                
              </div>     
             </div> 
             <a id='ok'></a>";

            if (_totalHtml == "") {
                _totalHtml = _baseHtml;
            }
            msg.Readed = true;
            webBrowser1.DocumentText = _totalHtml = _totalHtml.Replace("<a id='ok'></a>", "") + str;
        }
        /// <summary>
        ///同步自己发送链接
        /// </summary>
        private void ShowSendUrlMsg(WXMsg msg) {
            string _url_base64 = "data:img/jpg;base64,";
            string filena = null;
            if (_meUser == null || _friendUser == null) {
                return;
            }
            try {
                string picpath = path + "\\" + msg.MsgId + "small.jpg";   //链接配图
                if (File.Exists(picpath)) {
                    filena = picpath;
                    using (MemoryStream ms = new MemoryStream()) {
                        Bitmap url = new Bitmap(filena);
                        url.Save(ms, ImageFormat.Png);
                        _url_base64 = "data:img/jpg;base64," + Convert.ToBase64String(ms.ToArray());
                    }
                }
            }
            catch (Exception e){
                WriteLog.Writelog("ShowSendUrlMsg", e.ToString());
            }
            string str = @"
              <script type=""text/javascript"">window.location.hash = ""#ok"";</script> 
             <div style=""clear:both; "">
             <li style=""  margin-bottom:25px;"" > <div style=""margin-top:6px;color:white; background:#808080; width:60px; border-radius:5px; position: absolute; right: 50%;text-align: center; "" class="" chat_nick"">" + msg.Time.ToString("T") + @"</div></li>  
             
           <div style=""width:40px; height:40px; border-radius:20px;border:2px solid #ADFF2F; overflow:hidden;float:right;"">
            <img  id = ""imgPre"" class=""chat_content_avatar"" src=""" + _me_base64 + @""" style="" height: 40px; width: 40px;"">  
            </div>
              <div style=""float:right; top:5px; magin-right:-33px;  width:0; height:0; font-size:0; border:solid 8px;  margin-top:9px; border-color:#fff #fff #fff #AAAAAA; border-bottom-color:#fff;""></div>  
              <div onclick=""go();""  class= ""ss"" style=""float:right; border-radius:5px;  margin-top:-10px;padding:10px; font-family:微软雅黑;height: 100px; min-height:10px; width:auto; background:white;border:1px solid #AAAAAA; "">
                   <div style=""width:180px;height:50px;text-overflow: ellipsis;overflow:hidden;margin-top:-15px;"">
                       <p style=""text-overflow: ellipsis;overflow:hidden;font-size:13px;"">" + msg.FileName + @"</p>                       
                    </div>
                    <div style=""clear:both;height:50px;margin-top:10px;"">
                        <div style=""width:140px;height:60px;margin-top:-10px;text-overflow: ellipsis;overflow:hidden; float:left;line-height:10px;"">
                            <p style=""color:#AAAAAA;font-size:10px;"">" + msg.FileName + @"</p>
                        </div>
                        <div style""width:140;float:right;"">
                            <img src=""" + _url_base64 + @""" width=""38px"" height=""38px"" />
                        </div>
                    </div> 
               </div>     
             </div> 
             <a id='ok'></a>";

            if (_totalHtml == "") {
                _totalHtml = _baseHtml;
            }
            msg.Readed = true;
            webBrowser1.DocumentText = _totalHtml = _totalHtml.Replace("<a id='ok'></a>", "") + str;
        }
        /// <summary>
        /// UI界面显示发送名片
        /// </summary>
        /// <param name="w"></param>
        /// <returns></returns>
        private void ShowSendCard( WXMsg w ) {
            if (w == null || _friendUser == null)
                return ;
            string str = null;
            string tempName = null;

            //名字长度取舍
            if (w.Msg.Length > 10)
                tempName = w.Msg.Substring(0, 10);
            else
                tempName = w.Msg;

            //名片格式
            str = @"<script type=""text/javascript"">window.location.hash = ""#ok"";</script>
                            <div style=""clear:both;""><li style=""margin-bottom:13px; list-style:none;"">
                                <div style=""margin-top:6px; color:white; background:#808080; width:60px; border-radius:5px; position:absolute; right:50%; text-align:center;"">" + w.Time.ToLongTimeString() + @"</div>
                            </li>
                            <br />
                            <div style=""clear:both; margin:15px 0 0 0;"">
                               <div style=""width:40px; height:40px; border-radius:20px;border:2px solid #ADFF2F; overflow:hidden;float:right;"">
                               <img  id = ""imgPre"" class=""chat_content_avatar"" src=""" + _me_base64 + @""" style="" height: 40px; width: 40px;"">  
                               </div>
                                <div onclick=""go();"" class=""ss"" style = ""border:1px solid Gray; height:100px; width:300px; float:right; margin:0 5px 0 0; border-radius:5px; cursor:pointer;"">
                                    <div style = ""height:20px; border-bottom:1px #33CC66 solid; padding:8px 5px 2px 5px; width:90%; margin:0 0 0 3%; text-align:left;"">名片</div>
                                    <div style=""height:70px; line-height:70px;"">
                                        <div style = ""float:left; margin:5px 0 5px 3%;""><img src = """ + w.MsgId + @""" style=""border-radius:60px;"" height=""60"" width=""60""/></div>
                                        <div style = ""float:left; margin-left:10px;"">&nbsp;" + tempName + @"</div>
                                    </div>
                                </div>
                            </div>
                            </div></div>
                            <a id='ok'></a>";

            //显示
            if (_totalHtml.Equals(string.Empty))
                _totalHtml = _baseHtml;
            w.Readed = true;
            webBrowser1.DocumentText = _totalHtml = _totalHtml.Replace("<a id='ok'></a>", "") + str;
        } 
        #endregion

        #region 显示接受消息
        /// <summary>
        /// UI界面显示接收消息
        /// </summary>
        private void ShowReceiveMsg(WXMsg msg) {
            string Group_Content = "";
            string gro_headimg = "";
            string gro_nickname = "";
            if (_meUser == null || _friendUser == null) {
                return;
            }
            if (msg.IsGroup) {
                try {
                    string path = WChat.path.paths;
                    if (!Directory.Exists(path))
                        Directory.CreateDirectory(path);
                    string picpath = path + "\\" + msg.CrewNickName + ".jpg";
                    if (!File.Exists(picpath)) {
                        //Image gi = _friendUser.GrIcon(msg.CrewUserName);
                        //  using (MemoryStream ms = new MemoryStream()) {
                        //      gi.Save(ms, ImageFormat.Png);    //将图像转为base64提供第一次显示
                        //     _gro_base64 = "data:img/jpg;base64," + Convert.ToBase64String(ms.ToArray());
                        // }
                      //  gi.Save(picpath);   //将图像存储到本地
                       // gro_headimg = _gro_base64;
                        gro_headimg = _friend_base64;
                    } else {
                        using (MemoryStream ms = new MemoryStream()) {
                            Bitmap b = new Bitmap(picpath);
                            b.Save(ms, ImageFormat.Png);
                            _gro_base64 = "data:img/jpg;base64," + Convert.ToBase64String(ms.ToArray());
                        }
                        gro_headimg = _gro_base64;
                    }
                    gro_nickname = msg.CrewNickName;
                } catch { } 
            }
            else {
                Group_Content = msg.Msg;
                gro_headimg = _friend_base64 ;
                gro_nickname = _friendUser.ShowName;
            }
            string str = @"
           <script type=""text/javascript"">window.location.hash = ""#ok"";</script>
           <div style=""clear:both; width: 100%;"" >
           <li style=""  margin-bottom:13px;"" > <div style=""margin-top:6px;color:white; background:#808080; width:60px; border-radius:5px; position: absolute; right: 50%;text-align: center; "" class="" chat_nick"">" + msg.Time.ToString("T") + @"</div></li>  
           
           <div style=""width:40px; height:40px; border-radius:20px;border:2px solid #ADFF2F; overflow:hidden;float:left;"">
            <img  id = ""imgPre"" class=""chat_content_avatar"" src=""" + gro_headimg + @""" style=""height: 40px; width: 40px;"">
           </div>
            <p style=""margin-left:50px; color:gray; "" class="" chat_nick"">" + gro_nickname + @"</p>  
           <div style=""float:left;  top:5px; right:-16px;  width:0; height:0; font-size:0; border:solid 8px;  margin-top:-2px; border-color:#fff #e6e6fa #fff #fff; border-bottom-color:#fff;""></div>  
           <div class= ""ss""  onclick=""go();"" style=""float:left;  margin-top:-8px;  padding-top: 10px; padding-bottom: 10px; border-radius:5px; padding-left: 10px; padding-right: 10px; font-family:微软雅黑; height: auto; min-height:10px; width:auto; max-width:300px; background:#e6e6fa;""> <p class=""div"" style=""margin:0px auto;"">" +ConvertToGif(msg.Msg) + @"</p> </div>    
           </div>    
           <a id='ok'></a>";

            if (_totalHtml == "") {
                _totalHtml = _baseHtml;
            }
            msg.Readed = true;
            webBrowser1.DocumentText = _totalHtml = _totalHtml.Replace("<a id='ok'></a>", "") + str;

        }
        /// <summary>
        /// UI界面显示接收图片
        /// </summary>
        private void ShowReceivePIC( WXMsg msg ) {
            if (_meUser == null || _friendUser == null) {   return;  }
            string gro_headimg = "";
            string gro_nickname = "";
            if (msg.IsGroup) {
                try {
                    string picpath = path + "\\" + msg.CrewNickName + ".jpg";
                    if (!File.Exists(picpath)) {
                        gro_headimg = _friend_base64;
                    }
                    else {
                        using (MemoryStream ms = new MemoryStream()) {
                            Bitmap b = new Bitmap(picpath);
                            b.Save(ms, ImageFormat.Png);
                            _gro_base64 = "data:img/jpg;base64," + Convert.ToBase64String(ms.ToArray());
                        }
                        gro_headimg = _gro_base64;
                    }
                    gro_nickname = msg.CrewNickName;
                }
                catch(Exception ) { }
            }
            else {
                gro_headimg = _friend_base64;
                gro_nickname = _friendUser.ShowName;
            }

            try {
                string picpath = path + "\\" + msg.MsgId + "small.jpg";
                if (!File.Exists(picpath)) {
                    _friendUser.Pic.Save(picpath);
                }
                using (MemoryStream ms = new MemoryStream()) {
                    Bitmap b = new Bitmap(picpath);
                    b.Save(ms, ImageFormat.Png);
                    recpic_base64 = "data:img/jpg;base64," + Convert.ToBase64String(ms.ToArray());
                }
            }
            catch { }
            string str = @"
           <script type=""text/javascript"">window.location.hash = ""#ok"";</script>
           <div style=""clear:both; width: 100%;"" >
           <li style=""  margin-bottom:25px;"" > <div style=""margin-top:6px;color:white; background:#808080; width:60px; border-radius:5px; position: absolute; right: 50%;text-align: center; "" class="" chat_nick"">" + msg.Time.ToString("T") + @"</div></li>  
           
           <div style=""width:40px; height:40px; border-radius:20px;border:2px solid #ADFF2F; overflow:hidden;float:left;"">
            <img  id = ""imgPre"" class=""chat_content_avatar"" src=""" + gro_headimg + @""" style=""height: 40px; width: 40px;"">
           </div>
            <p style=""margin-left:50px; color:gray; "" class="" chat_nick"">" + gro_nickname + @"</p>  
           <div style=""float:left;  top:5px; right:-16px;  width:0; height:0; font-size:0; border:solid 8px;  margin-top:-2px; border-color:#fff #e6e6fa #fff #fff; border-bottom-color:#fff;""></div>  
           <div onclick=""go();"" class= ""ss""  style=""float:left; border-radius:5px;  margin-top:-8px; padding: 10px; font-family:微软雅黑; margin-left:0px;height: auto; min-height:10px; width:auto; max-width:300px; background:#e6e6fa; ""><img src=""" + recpic_base64 + @""" /></div>    
           </div>    
           <a id='ok'></a>";

            if (_totalHtml == "") {
                _totalHtml = _baseHtml;
            }
            msg.Readed = true;
            webBrowser1.DocumentText = _totalHtml = _totalHtml.Replace("<a id='ok'></a>", "") + str;
        }
        /// <summary>
        /// UI界面显示语音
        /// </summary>
        private void ShowReceiveVoice( WXMsg msg ) {
            if (_meUser == null || _friendUser == null) {
                return;
            }
            string headimg = "";
            string nickname = "";
            if (msg.IsGroup) {
                try {
                    string picpath = path + "\\" + msg.CrewNickName + ".jpg";
                    if (!File.Exists(picpath)) {
                        headimg = _friend_base64;
                    }
                    else {
                        using (MemoryStream ms = new MemoryStream()) {
                            Bitmap b = new Bitmap(picpath);
                            b.Save(ms, ImageFormat.Png);
                            _gro_base64 = "data:img/jpg;base64," + Convert.ToBase64String(ms.ToArray());
                        }
                        headimg = _gro_base64;
                    }
                    nickname = msg.CrewNickName;
                }
                catch (Exception) { }
            }
            else {
                headimg = _friend_base64;
                nickname = _friendUser.ShowName;
            }

            using (MemoryStream ms = new MemoryStream()) {
                string picpath = msg.FileName;
                Bitmap backImage = new Bitmap(this.GetType(), "voice_left.png");
                Bitmap b = new Bitmap(backImage);
                b.Save(ms, ImageFormat.Png);
                _Voi_base64 = "data:img/jpg;base64," + Convert.ToBase64String(ms.ToArray());
            }
            string str = @"
           <script type=""text/javascript"">window.location.hash = ""#ok"";</script>
           <div style=""clear:both; width: 100%;"" >
           <li style=""  margin-bottom:25px;"" > <div style=""margin-top:6px;color:white; background:#808080; width:60px; border-radius:5px; position: absolute; right: 50%;text-align: center; "" class="" chat_nick"">" + msg.Time.ToString("T") + @"</div></li>  
           
           <div style=""width:40px; height:40px; border-radius:20px;border:2px solid #ADFF2F; overflow:hidden;float:left;"">
            <img  id = ""imgPre"" class=""chat_content_avatar"" src=""" + headimg + @""" style=""height: 40px; width: 40px;"">
           </div>
            <p style=""margin-left:50px; color:gray; "" class="" chat_nick"">" + nickname + @"</p>  
           <div style=""float:left;  top:5px; right:-16px;  width:0; height:0; font-size:0; border:solid 8px;  margin-top:-2px; border-color:#fff #e6e6fa #fff #fff; border-bottom-color:#fff;""></div>  
           <div onclick=""go();"" class= ""ss""  style=""float:left; border-radius:5px; padding-top: 10px; padding-left: 10px;  margin-top:-8px;  font-family:微软雅黑; margin-left:0px; height: 30px; width:60px; max-width:300px; background:#e6e6fa; ""><img src=""" + _Voi_base64 + @""" /></div>    
           </div>    
           <a id='ok'></a>";

            if (_totalHtml == "") {
                _totalHtml = _baseHtml;
            }
            msg.Readed = true;
            webBrowser1.DocumentText = _totalHtml = _totalHtml.Replace("<a id='ok'></a>", "") + str;
        }
        /// <summary>
        /// UI界面显示接收名片
        /// </summary>
        /// <param name="w"></param>
        /// <returns></returns>
        private string ShowReceiveCard( WXMsg w ) {
            if (w == null || _friendUser == null)  return string.Empty;
            string str = null;
            string tempName = null;
            string headimg = "";
            string nickname = "";
            if (w.IsGroup) {
                try {
                    string picpath = path + "\\" + w.CrewNickName + ".jpg";
                    if (!File.Exists(picpath)) {
                        headimg = _friend_base64;
                    }
                    else {
                        using (MemoryStream ms = new MemoryStream()) {
                            Bitmap b = new Bitmap(picpath);
                            b.Save(ms, ImageFormat.Png);
                            _gro_base64 = "data:img/jpg;base64," + Convert.ToBase64String(ms.ToArray());
                        }
                        headimg = _gro_base64;
                    }
                    nickname = w.CrewNickName;
                }
                catch (Exception) { }
            }
            else {
                headimg = _friend_base64;
                nickname = _friendUser.ShowName;
            }

            //名字长度取舍
            if (w.Msg.Length > 10)
                tempName = w.Msg.Substring(0, 10);
            else
                tempName = w.Msg;

            //名片格式
            str = @"<script type=""text/javascript"">window.location.hash = ""#ok"";</script>
                            <div style=""clear:both;""><li style=""margin-bottom:13px; list-style:none;"">
                                <div style=""margin-top:6px; color:white; background:#808080; width:60px; border-radius:5px; position:absolute; right:50%; text-align:center;"">" + w.Time.ToLongTimeString() + @"</div>
                            </li>
                            <br />
                            <div style=""clear:both; margin:15px 0 0 0;"">
                                <div style=""width:40px; height:40px; border-radius:20px;border:2px solid #ADFF2F; overflow:hidden;float:left;"">
                                <img  id = ""imgPre"" class=""chat_content_avatar"" src=""" + _friend_base64 + @""" style=""height: 40px; width: 40px;"">
                                </div>
                                <div onclick=""go();"" class=""ss"" style = ""border:1px solid Gray; height:100px; width:300px; float:left; margin:0 0 0 5px; border-radius:5px; cursor:pointer;"">
                                    <div style = ""height:20px; border-bottom:1px #33CC66 solid; padding:8px 5px 2px 5px; width:90%; margin:0 0 0 3%; text-align:left;"">名片</div>
                                    <div style=""height:70px; line-height:70px;"">
                                        <div style = ""float:left; margin:5px 0 5px 3%;""><img src = """ + w.MsgId + @""" style=""border-radius:60px;"" height=""60"" width=""60""/></div>
                                        <div style = ""float:left; margin-left:10px;"">&nbsp;" + tempName + @"</div>
                                    </div>
                                </div>
                            </div>
                            </div></div>
                            <a id='ok'></a>";

            //显示
            if (_totalHtml.Equals(string.Empty))
                _totalHtml = _baseHtml;
            w.Readed = true;
            webBrowser1.DocumentText = _totalHtml = _totalHtml.Replace("<a id='ok'></a>", "") + str;
            return str;
        }
        /// <summary>
        /// UI界面显示接收文件
        /// </summary>
        private void ShowReceiveFileMsg(WXMsg msg) {
            if (_meUser == null || _friendUser == null) {
                return;
            }
            string headimg = "";
            string nickname = "";
            if (msg.IsGroup) {
                try {
                    string picpath = path + "\\" + msg.CrewNickName + ".jpg";
                    if (!File.Exists(picpath)) {
                        headimg = _friend_base64;
                    }
                    else {
                        using (MemoryStream ms = new MemoryStream()) {
                            Bitmap b = new Bitmap(picpath);
                            b.Save(ms, ImageFormat.Png);
                            _gro_base64 = "data:img/jpg;base64," + Convert.ToBase64String(ms.ToArray());
                        }
                        headimg = _gro_base64;
                    }
                    nickname = msg.CrewNickName;
                }
                catch (Exception) { }
            }
            else {
                headimg = _friend_base64;
                nickname = _friendUser.ShowName;
            }

            using (MemoryStream ms = new MemoryStream()) {
                string picpath = msg.FileName;
                Bitmap backImage = new Bitmap(this.GetType(), "file.jpg");
                Bitmap b = new Bitmap(backImage);
                b.Save(ms, ImageFormat.Png);
                _fil_base64 = "data:img/jpg;base64," + Convert.ToBase64String(ms.ToArray());
            }
            string str = @"
           <script type=""text/javascript"">window.location.hash = ""#ok"";</script>
           <div style=""clear:both; width: 100%;"" >
           <li style=""  margin-bottom:25px;"" > <div style=""margin-top:6px;color:white; background:#808080; width:60px; border-radius:5px; position: absolute; right: 50%;text-align: center; "" class="" chat_nick"">" + msg.Time.ToString("T") + @"</div></li>  
           <div style=""width:40px; height:40px; border-radius:20px;border:2px solid #ADFF2F; overflow:hidden;float:left;"">
                <img  id = ""imgPre"" class=""chat_content_avatar"" src=""" + _friend_base64 + @""" style=""height: 40px; width: 40px; "">
           </div>
           <p style=""margin-left:50px; color:gray; "" class="" chat_nick"">" + _friendUser.ShowName + @"</p>  
           <div style=""float:left;  top:5px; right:-16px;  width:0; height:0; font-size:0; border:solid 8px;  margin-top:-2px; border-color:#fff #AAAAAA #fff #fff; border-bottom-color:#fff;""></div> 
           <div onclick=""go();""  class= ""ss"" style=""float:left; border-radius:5px; padding:10px;  margin-top:-10px; font-family:微软雅黑;height: 80px; min-height:10px; width:auto; background:white;border:1px solid #AAAAAA; "">                     
                    <div style=""width:140px;height:50px;text-overflow: ellipsis;overflow:hidden;margin-top:-10px; float:left;line-height:13px;"">
                       <p style=""text-overflow: ellipsis;overflow:hidden;font-size:14px;"">" + msg.FileName + @"</p>
                       <p style=""color:#AAAAAA;font-size:10px;"">" + msg.FileSize+"B" + @"</p>
                    </div>
                    <div style""width:140;float:right;"">
                       <img src="""+ _fil_base64 + @""" width =""30px"" />
                    </div>
                    <hr color=""#DDDDDD"" /> 
                    <p style=""margin:0px;font-size:10px;color:#AAAAAA;"">环球云控</p>    
           </div>
           </div>    
           <a id='ok'></a>";

            if (_totalHtml == "") {
                _totalHtml = _baseHtml;
            }
            msg.Readed = true;
            webBrowser1.DocumentText = _totalHtml = _totalHtml.Replace("<a id='ok'></a>", "") + str;

        }
        /// <summary>
        /// UI界面显示接收链接
        /// </summary>
        private void ShowReceiveUrlMsg(WXMsg msg) {
            string _url_base64 = "data:img/jpg;base64,";
            string filena = null;
            if (_meUser == null || _friendUser == null) { return;   }    
            string headimg = "";
            string nickname = "";
            if (msg.IsGroup) {
                try {
                    string picpath = path + "\\" + msg.CrewNickName + ".jpg";
                    if (!File.Exists(picpath)) {
                        headimg = _friend_base64;
                    }
                    else {
                        using (MemoryStream ms = new MemoryStream()) {
                            Bitmap b = new Bitmap(picpath);
                            b.Save(ms, ImageFormat.Png);
                            _gro_base64 = "data:img/jpg;base64," + Convert.ToBase64String(ms.ToArray());
                        }
                        headimg = _gro_base64;
                    }
                    nickname = msg.CrewNickName;
                }
                catch (Exception) { }
            }
            else {
                headimg = _friend_base64;
                nickname = _friendUser.ShowName;
            }

            try {
                string picpath = path + @"\\" + msg.MsgId + "small.jpg";
                if (File.Exists(picpath)) {
                    filena = picpath;
                    using (MemoryStream ms = new MemoryStream()) {
                        Bitmap url = new Bitmap(filena);
                        url.Save(ms, ImageFormat.Png);
                        _url_base64 = "data:img/jpg;base64," + Convert.ToBase64String(ms.ToArray());
                    }
                }
            }
            catch { }
            string str = @"
           <div style=""clear:both; width: 100%;"" >
           <li style=""  margin-bottom:25px;"" > <div style=""margin-top:6px;color:white; background:#808080; width:60px; border-radius:5px; position: absolute; right: 50%;text-align: center; "" class="" chat_nick"">" + msg.Time.ToString("T") + @"</div></li>            
           <div style=""width:40px; height:40px; border-radius:20px;border:2px solid #ADFF2F; overflow:hidden;float:left;"">
                <img  id = ""imgPre"" class=""chat_content_avatar"" src=""" + headimg + @""" style=""height: 40px; width: 40px;"">
           </div>
           <p style=""margin-left:50px; color:gray; "" class="" chat_nick"">" + nickname + @"</p>  
           <div style=""float:left;  top:5px; right:-16px;  width:0; height:0; font-size:0; border:solid 8px;  margin-top:-2px; border-color:#fff #AAAAAA #fff #fff; border-bottom-color:#fff;""></div> 
           <div onclick=""go();""  class= ""ss"" style=""float:left; border-radius:5px;  margin-top:-10px;padding:10px; font-family:微软雅黑;height: 100px; min-height:10px; width:auto; background:white;border:1px solid #AAAAAA; "">                     
                    <div style=""width:180px;height:50px;text-overflow: ellipsis;overflow:hidden;margin-top:-15px"">
                       <p style=""text-overflow: ellipsis;overflow:hidden;font-size:14px;"">" + msg.FileName + @"</p>                       
                    </div>
                    <div style=""clear:both;"">
                        <div style=""width:140px;height:60px;text-overflow: ellipsis;overflow:hidden;margin-top:-10px; float:left;line-height:10px;"">
                            <p style=""color:#AAAAAA;font-size:10px;"">" + msg.FileName + @"</p>
                        </div>
                        <div style""width:140;float:right;"">
                            <img src=""" + _url_base64 + @""" width=""38px"" height=""38px"" />
                        </div>
                    </div>  
           </div>
           </div>
           <a id='ok'></a>";

            if (_totalHtml == "") {
                _totalHtml = _baseHtml;
            }
            msg.Readed = true;
            webBrowser1.DocumentText = _totalHtml = _totalHtml.Replace("<a id='ok'></a>", "") + str;

        }
        /// <summary>
        /// UI界面显示接收链接 
        /// </summary>
        private void ShowReceiveVerifyMsg(WXMsg msg) {
            if (_meUser == null || _friendUser == null) {
                return;
            }
            string str = @" 
           <script type=""text/javascript"">window.location.hash = ""#ok"";</script>
           <div style=""clear:both; width: 100%;"">
           <li style=""  margin-bottom:25px;"" > <div style=""margin-top:6px;color:white; background:#808080; width:60px; border-radius:5px; position: absolute; right: 50%;text-align: center; "" class="" chat_nick"">" + msg.Time.ToString("T") + @"</div></li>  
           
           <div style=""width:40px; height:40px; border-radius:20px;border:2px solid #ADFF2F; overflow:hidden;float:left;"">
            <img  id = ""imgPre"" class=""chat_content_avatar"" src=""" + _friend_base64 + @""" style=""height: 40px; width: 40px;"">
            </div>
           <p style=""margin-left:50px; color:gray; "" class="" chat_nick"">" + _friendUser.ShowName + @"</p>  
           <div style=""float:left;  top:5px; right:-16px;  width:0; height:0; font-size:0; border:solid 8px;  margin-top:-2px; border-color:#fff #AAAAAA #fff #fff; border-bottom-color:#fff;""></div> 
           <div onclick=""go();"" class= ""ss"" style=""float:left; border-radius:5px;  margin-top:-10px;padding:10px; font-family:微软雅黑;height: 100px; min-height:10px; width:auto; background:white;border:1px solid #AAAAAA; "">                     
                    <div style=""width:140px;height:40px;margin-top:-15px"">
                       <p style=""text-overflow: ellipsis;overflow:hidden;font-size:14px;"">" + msg.Msg + @"</p>                       
                    </div>
                    <div style=""clear:both;"">
                        <div style=""width:140px;height:60px;margin-top:-10px; float:left;line-height:10px;"">
                            <p style=""color:#AAAAAA;font-size:10px;text-overflow: ellipsis;overflow:hidden;white-space:nowrap;"">" + msg.V_Content + @"</p>
                        </div>
                        <div style""width:140;float:right;"">
                           <input type=""button"" value=""通过验证"" style=""color=#808080;""></input>
                        </div>
                    </div> 
                    <hr color=""#DDDDDD"" /> 
                    <p style=""margin:0px;font-size:10px;color:#AAAAAA;margin-top:-5px;"">环球云控</p>
           </div>
           </div>    
           <a id='ok'></a>";


            if (_totalHtml == "") {
                _totalHtml = _baseHtml;
            }
            msg.Readed = true;
            webBrowser1.DocumentText = _totalHtml = _totalHtml.Replace("<a id='ok'></a>", "") + str;

        }
        #endregion

        #region 界面显示初始化

        private string _totalHtml = "";
        private string _baseHtml = @"<html><head>
        <meta http-equiv=""X-UA-Compatible"" content=""IE=9""/>
        <script type=""text/javascript"">

        var oli;
              function go(){  
                  bool= ""1"";
     
                  var e=window.event;
                  oli = document.getElementsByClassName('ss');
                  for(var i=0; i< oli.length;i++)
                  {
                      oli[i].index=i;
                      oli[i].onmousedown=function aa(){
                          if(e.button == ""1"")
                              window.external.getContext(this.index);
                          else if(e.button == ""2"")
                               window.external.getRight(this.index);
                      }
                  }
                oli=null;
              };

        </script>
        </head>
        <body onload=""window.scrollTo(0,document.body.scrollHeight);"" ><li style="" margin-bottom:13px; "" ><center><a onmousedown=""loadmore();"" id='ok' style="" color:#5CACEE; font-size:13px; "" >查看更多消息，请转到消息管理</a></center></li></body></html>";

        #endregion

        /// <summary>
        /// 表情转换
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        private string ConvertToGif( string text ) {
            string ctent = "";
            if (text.IndexOf("[") > -1) {
                StringToUrl getUrl = new WChat.StringToUrl();
                Regex reg = new Regex(@"\[(.+?)]");
                List<string> asd_string = new List<string>();
                foreach (Match asd in reg.Matches(text)) {
                    asd_string.Add(asd.Groups[1].ToString());
                    for (int i = 0; i < asd_string.Count; i++) {
                        ctent = text.Replace(asd_string[i], "");
                    }
                    text = ctent.Replace("[]", getUrl.GetEmUrl(asd.Groups[1].ToString()));
                }
                return text;
            }
            return text;
        }
        #endregion

        #region 第一次在界面上显示消息
        private void ShowFirstMsg() {
            this.BeginInvoke((Action)delegate () {
                List<WXMsg> limsg = new List<WXMsg>();
                limsg = ss.GetChatLog(_meUser.Myuin, _friendUser.NickName);
                string msg = @"<script type=""text/javascript""> window.scrollTo(0,document.body.scrollHeight); </script>";
                piczoom.Clear();
                for (int i = limsg.Count - 1; i >= 0; i--) {
                    piczoom.Add(limsg[i]);
                    if (limsg[i].IsReceive == 1) {
                        msg += ShowSend(limsg[i]);
                    }
                    else {
                        msg += ShowReceive(limsg[i]);
                    }
                    msg += @"<a id='ok'></a>";
                }
                if (_totalHtml == "") {
                    _totalHtml = _baseHtml;
                }
                webBrowser1.DocumentText = _totalHtml = _totalHtml.Replace("<a id='ok'></a>", "") + msg;
            });
        }

        private string showsendmsg( WXMsg msg ) {
            if (_meUser == null || _friendUser == null) {  return null;}
            string str = @"  
             <div style=""clear:both; "">
             <li style=""  margin-bottom:13px;"" > <div style=""margin-top:6px;color:white; background:#808080; width:60px; border-radius:5px; position: absolute; right: 50%;text-align: center; "" class="" chat_nick"">" + msg.Time.ToString("T") + @"</div></li>  
             <div style=""width:40px; height:40px; border-radius:20px;border:2px solid #ADFF2F; overflow:hidden;float:right;"">
             <img  id = ""imgPre"" class=""chat_content_avatar"" src=""" + _me_base64 + @""" style="" height: 40px; width: 40px;"">
             </div>
             <div style=""float:right; top:5px; magin-right:-33px;  width:0; height:0; font-size:0; border:solid 8px;  margin-top:9px; border-color:#fff #fff #fff #32cd32; border-bottom-color:#fff;""></div>  
             <div  class= ""ss""  onclick=""go();"" style=""float:right; color:white; padding-top: 10px; padding-bottom: 10px; border-radius:5px; padding-left: 10px;padding-right: 10px; font-family:微软雅黑; height: auto; min-height:10px; width:auto; max-width:300px; background:#32cd32;""> <p class=""div"" style=""margin:0px auto;"">" + ConvertToGif(msg.Msg) + @"</p>  </div>    
             </div>";
            return str;
        }
        private string showsendpic( WXMsg msg ) {
            if (_meUser == null || _friendUser == null) {   return null;     }
            try {
                string picpath = path + "\\" + msg.MsgId + "small.jpg";
                if (File.Exists(picpath)) {
                    using (MemoryStream ms = new MemoryStream()) {
                        Bitmap b = new Bitmap(picpath);
                        b.Save(ms, ImageFormat.Png);
                        sendpic_base64 = "data:img/jpg;base64," + Convert.ToBase64String(ms.ToArray());
                        b.Dispose();
                    }
                }
            } catch(Exception e) {
                WriteLog.Writelog("showsendpic", e.ToString());
            }
           
            string str = @"
             <div style=""clear:both; "">
             <li style=""  margin-bottom:13px;"" > <div style=""color:white;margin-top:6px; background:#808080; width:60px; border-radius:5px; position: absolute; right: 50%;text-align: center; "" class="" chat_nick"">" + msg.Time.ToString("T") + @"</div></li>  
             <div style=""width:40px; height:40px; border-radius:20px;border:2px solid #ADFF2F; overflow:hidden;float:right;"">

             <img  id = ""imgPre"" class=""chat_content_avatar"" src=""" + _me_base64 + @""" style="" height: 40px; width: 40px;"">
             </div> 
            
             <div style=""float:right; top:5px; magin-right:-33px;  width:0; height:0; font-size:0; border:solid 8px;  margin-top:9px; border-color:#fff #fff #fff #32cd32; border-bottom-color:#fff;""></div>  
             <div  class= ""ss""   onclick=""go();"" style=""float:right; color:white; padding-top: 10px; padding-bottom: 10px; border-radius:5px; padding-left: 10px;padding-right: 10px; font-family:微软雅黑; height: auto; min-height:10px; width:auto; max-width:300px; background:#32cd32;""><img src=""" + sendpic_base64 + @""" /></div>     
             </div> ";
            return str;
        }
        private string showlocpic( WXMsg msg ) {
            if (_meUser == null || _friendUser == null) {  return null;  }
            if (msg != null)  //图片
              {
                try {
                    using (MemoryStream ms = new MemoryStream()) {
                        string picpath = msg.FileName;
                        if (File.Exists(picpath)) {
                            Bitmap b = new Bitmap(picpath);
                            b.Save(ms, ImageFormat.Png);
                            _locicon_base64 = "data:img/jpg;base64," + Convert.ToBase64String(ms.ToArray());
                            b.Dispose();
                        }
                    }
                } catch (Exception e) {
                    WriteLog.Writelog("showlocpic", e.ToString());
                }
            }
            string str = @"
            <div style=""clear:both; "">
            <li style=""  margin-bottom:13px;"" > <div style=""margin-top:6px;color:white; background:#808080; width:60px; border-radius:5px; position: absolute; right: 50%;text-align: center; "" class="" chat_nick"">" + msg.Time.ToString("T") + @"</div></li>  
             
            <div style=""width:40px; height:40px; border-radius:20px;border:2px solid #ADFF2F; overflow:hidden;float:right;"">
            <img  id = ""imgPre"" class=""chat_content_avatar"" src=""" + _me_base64 + @""" style="" height: 40px; width: 40px;"">  
            </div>
            <div style=""float:right; top:5px; magin-right:-45px;  width:0; height:0; font-size:0; border:solid 8px;  margin-top:9px; border-color:#fff #fff #fff #32cd32; border-bottom-color:#fff;""></div>  
            <div  class= ""ss""   onclick=""go();"" style=""float:right;color:white; padding-top: 10px; padding-bottom: 10px; border-radius:5px; padding-left: 10px;padding-right: 10px; font-family:微软雅黑; height: auto; min-height:10px; width:auto; max-width:300px; background:#32cd32;"">
            <img src=""" + _locicon_base64 + @""" width =""80px""  />
            </div>    
            </div> ";
            return str;
        }
        private string showsendfilemsg( WXMsg msg ) {
            if (_meUser == null || _friendUser == null) {
                return null;
            }
            using (MemoryStream ms = new MemoryStream()) {
                string picpath = msg.FileName;
                Bitmap backImage = new Bitmap(this.GetType(), "file.jpg");
                Bitmap b = new Bitmap(backImage);
                b.Save(ms, ImageFormat.Png);
                _fil_base64 = "data:img/jpg;base64," + Convert.ToBase64String(ms.ToArray());
            }
            string str = @"
              <div style=""clear:both; "">
              <li style=""  margin-bottom:25px;"" > <div style=""margin-top:6px;color:white; background:#808080; width:60px; border-radius:5px; position: absolute; right: 50%;text-align: center; "" class="" chat_nick"">" + msg.Time.ToString("T") + @"</div></li>  
            
               <div style=""width:40px; height:40px; border-radius:20px;border:2px solid #ADFF2F; overflow:hidden;float:right;"">
               <img  id = ""imgPre"" class=""chat_content_avatar"" src=""" + _me_base64 + @""" style="" height: 40px; width: 40px;"">  
               </div>
               <div style=""float:right; top:5px; magin-right:-33px;  width:0; height:0; font-size:0; border:solid 8px;  margin-top:9px; border-color:#fff #fff #fff #AAAAAA; border-bottom-color:#fff;""></div>  
               
                <div onclick=""go();""  class= ""ss"" style=""float:right; border-radius:5px;  margin-top:-13px; padding: 10px; font-family:微软雅黑; margin-left:0px;height: 80px; min-height:10px; width:auto; background:white; border:1px solid #AAAAAA;"">                    
                <div style=""width:140px;height:50px;text-overflow: ellipsis;overflow:hidden;margin-top:-10px; float:left;line-height:13px;"">
                <p style=""text-overflow: ellipsis;overflow:hidden;font-size:14px;"">" + msg.Msg + @"</p>
                <p style=""color:#AAAAAA;font-size:10px;"">" + msg.FileSize + "B" + @"</p>
                </div>
                <div style""width:140;float:right;"">
                <img src=""" + _fil_base64 + @""" width =""30px""/>
                </div>
                <hr color=""#DDDDDD"" /> 
                <p style=""margin:0px;font-size:10px;color:#AAAAAA;"">环球云控</p>                          
                </div>     
                </div> ";
            return str;
        }
        private string showsendurlmsg( WXMsg msg ) {
            string _url_base64 = "data:img/jpg;base64,";
            string filena = null;
            if (_meUser == null || _friendUser == null) {  return null;  }
            try {
                string picpath = path + "\\" + msg.MsgId + "small.jpg";
                if (File.Exists(picpath)) {
                    filena = picpath;
                    using (MemoryStream ms = new MemoryStream()) {
                        Bitmap url = new Bitmap(filena);
                        url.Save(ms, ImageFormat.Png);
                        _url_base64 = "data:img/jpg;base64," + Convert.ToBase64String(ms.ToArray());
                    }
                }
            }catch (Exception e) {
                WriteLog.Writelog("showsendurlmsg", e.ToString());
            }
            
            string str = @"
             <div style=""clear:both; "">
             <li style=""  margin-bottom:13px;"" > <div style=""margin-top:6px;color:white; background:#808080; width:60px; border-radius:5px; position: absolute; right: 50%;text-align: center; "" class="" chat_nick"">" + msg.Time.ToString("T") + @"</div></li>  
             
             <div style=""width:40px; height:40px; border-radius:20px;border:2px solid #ADFF2F; overflow:hidden;float:right;"">
             <img  id = ""imgPre"" class=""chat_content_avatar"" src=""" + _me_base64 + @""" style="" height: 40px; width: 40px;"">  
             </div>
             <div style=""float:right; top:5px; magin-right:-33px;  width:0; height:0; font-size:0; border:solid 8px;  margin-top:9px; border-color:#fff #fff #fff #AAAAAA; border-bottom-color:#fff;""></div>  
             <div onclick=""go();""  class= ""ss"" style=""float:right; border-radius:5px;  margin-top:-10px;padding:10px; font-family:微软雅黑;height: 100px; min-height:10px; width:auto; background:white;border:1px solid #AAAAAA; "">
             <div style=""width:180px;height:50px;text-overflow: ellipsis;overflow:hidden;margin-top:-15px;"">
             <p style=""text-overflow: ellipsis;overflow:hidden;font-size:13px;"">" + msg.FileName + @"</p>                       
             </div>
             <div style=""clear:both;height:50px"">
             <div style=""width:140px;height:60px;text-overflow: ellipsis;overflow:hidden;margin-top:-10px; float:left;line-height:10px;"">
             <p style=""color:#AAAAAA;font-size:10px;"">" + msg.FileName + @"</p>
             </div>
             <div style""width:140;float:right;"">
             <img src=""" + _url_base64 + @""" width=""38px"" height=""38px"" />
             </div>
             </div> 
                   
             </div>     
             </div> ";
            return str;
        }
        private string showsendcard( WXMsg w ) {
            if (w == null || _friendUser == null)
                return string.Empty;
            string str = null;
            string tempName = null;

            //名字长度取舍
            if (w.Msg.Length > 10)
                tempName = w.Msg.Substring(0, 10);
            else
                tempName = w.Msg;

            //名片格式
            str = @"<script type=""text/javascript"">window.location.hash = ""#ok"";</script>
                            <div style=""clear:both;""><li style=""margin-bottom:13px; list-style:none;"">
                                <div style=""margin-top:6px; color:white; background:#808080; width:60px; border-radius:5px; position:absolute; right:50%; text-align:center;"">" + w.Time.ToLongTimeString() + @"</div>
                            </li>
                            <br />
                            <div style=""clear:both; margin:15px 0 0 0;"">
                               <div style=""width:40px; height:40px; border-radius:20px;border:2px solid #ADFF2F; overflow:hidden;float:right;"">
                               <img  id = ""imgPre"" class=""chat_content_avatar"" src=""" + _me_base64 + @""" style="" height: 40px; width: 40px;"">
                               </div>
                                <div onclick=""go();"" class=""ss"" style = ""border:1px solid Gray; height:100px; width:300px; float:right; margin:0 5px 0 0; border-radius:5px; cursor:pointer;"">
                                    <div style = ""height:20px; border-bottom:1px #33CC66 solid; padding:8px 5px 2px 5px; width:90%; margin:0 0 0 3%; text-align:left;"">名片</div>
                                    <div style=""height:70px; line-height:70px;"">
                                        <div style = ""float:left; margin:5px 0 5px 3%;""><img src = """ + w.MsgId + @""" style=""border-radius:60px;"" height=""60"" width=""60""/></div>
                                        <div style = ""float:left; margin-left:10px;"">&nbsp;" + tempName + @"</div>
                                    </div>
                                </div>
                            </div>
                            </div></div>";
            return str;
        }    //名片
        private string showsendvoice( WXMsg msg ) {
            if (_meUser == null || _friendUser == null) {  return null;   }
            try {
                using (MemoryStream ms = new MemoryStream()) {
                    Bitmap backImage = new Bitmap(this.GetType(), "voice_right.png");
                    Bitmap b = new Bitmap(backImage);
                    b.Save(ms, ImageFormat.Png);
                    _Voi_base64 = "data:img/jpg;base64," + Convert.ToBase64String(ms.ToArray());
                }
            } catch (Exception e) {
                WriteLog.Writelog("showsendvoice", e.ToString());
            }
           
            string str = @"<script type=""text/javascript"">window.location.hash = ""#ok"";</script> 
             <div style=""clear:both; "">
             <li style=""  margin-bottom:25px;"" > <div style=""color:white;margin-top:6px; background:#808080; width:60px; border-radius:5px; position: absolute; right: 50%;text-align: center; "" class="" chat_nick"">" + msg.Time.ToString("T") + @"</div></li>  
            <div style=""width:40px; height:40px; border-radius:20px;border:2px solid #ADFF2F; overflow:hidden;float:right;"">

            <img  id = ""imgPre"" class=""chat_content_avatar"" src=""" + _me_base64 + @""" style="" height: 40px; width: 40px;"">
            </div> 
            
             <div style=""float:right; top:5px; magin-right:-33px;  width:0; height:0; font-size:0; border:solid 8px;  margin-top:9px; border-color:#fff #fff #fff #32cd32; border-bottom-color:#fff;""></div>  
             <div  class= ""ss""  onclick=""go();"" style=""float:right; color:white; padding-top: 10px; padding-bottom: 5px; border-radius:5px;  font-family:微软雅黑; height:25px;  min-width:70px; max-width:300px; background:#32cd32;"">&nbsp &nbsp &nbsp &nbsp &nbsp <img src=""" + _Voi_base64 + @""" /></div>     
             </div> ";

            return str;

        }

        private string showreceivemsg( WXMsg msg ) {
            if (_meUser == null || _friendUser == null) {  return null;}   
            string headimg = "";
            string nickname = "";
            if (msg.IsGroup) {
                nickname = msg.CrewNickName;
                try {
                    string picpath = path + "\\" + msg.CrewNickName.Trim() + ".jpg";
                    if (File.Exists(picpath)) {
                        using (MemoryStream ms = new MemoryStream()) {
                            Bitmap b = new Bitmap(picpath);
                            b.Save(ms, ImageFormat.Png);
                            _gro_base64 = "data:img/jpg;base64," + Convert.ToBase64String(ms.ToArray());
                        }
                        headimg = _gro_base64;
                    } else {
                        headimg = _friend_base64;
                    }
                } catch (Exception e) {
                    WriteLog.Writelog("showreceivemsg", e.ToString());
                }
            }
            else {
                headimg = _friend_base64;
                nickname = _friendUser.ShowName;
            }

            string str = @"
           <script type=""text/javascript"">window.location.hash = ""#ok"";</script>
           <div style=""clear:both; width: 100%;"" >
           <li style=""  margin-bottom:13px;"" > <div style=""margin-top:6px;color:white; background:#808080; width:60px; border-radius:5px; position: absolute; right: 50%;text-align: center; "" class="" chat_nick"">" + msg.Time.ToString("T") + @"</div></li>  
           
           <div style=""width:40px; height:40px; border-radius:20px;border:2px solid #ADFF2F; overflow:hidden;float:left;"">
            <img  id = ""imgPre"" class=""chat_content_avatar"" src=""" + headimg + @""" style=""height: 40px; width: 40px;"">
           </div>
            <p style=""margin-left:50px; color:gray; "" class="" chat_nick"">" + nickname + @"</p>  
           <div style=""float:left;  top:5px; right:-16px;  width:0; height:0; font-size:0; border:solid 8px;  margin-top:-2px; border-color:#fff #e6e6fa #fff #fff; border-bottom-color:#fff;""></div>  
           <div class= ""ss""  onclick=""go();"" style=""float:left;  margin-top:-8px;  padding-top: 10px; padding-bottom: 10px; border-radius:5px; padding-left: 10px; padding-right: 10px; font-family:微软雅黑; height: auto; min-height:10px; width:auto; max-width:300px; background:#e6e6fa;""> <p class=""div"" style=""margin:0px auto;"">" + ConvertToGif(msg.Msg) + @"</p>  </div>    
           </div> ";  
       
            return str;
        }
        private string showreceivepic( WXMsg msg ) {
            if (_meUser == null || _friendUser == null) { return null;    }
            string headimg = "";
            string nickname = "";
            try {
                if (msg.IsGroup) {
                    nickname = msg.CrewNickName;
                    string headpath = path + "\\" + msg.CrewNickName.Trim() + ".jpg";
                    if (File.Exists(headpath)) {
                        using (MemoryStream ms = new MemoryStream()) {
                            Bitmap b = new Bitmap(headpath);
                            b.Save(ms, ImageFormat.Png);
                            _gro_base64 = "data:img/jpg;base64," + Convert.ToBase64String(ms.ToArray());
                        }
                        headimg = _gro_base64;
                    }
                    else {
                        headimg = _friend_base64;
                    }
                    /////////////////////////////////////////////////////////接受图片
                    string picpath = path + "\\" + msg.MsgId + "small.jpg";
                    if (File.Exists(picpath)) {
                        using (MemoryStream ms = new MemoryStream()) {
                            Bitmap b = new Bitmap(picpath);
                            b.Save(ms, ImageFormat.Png);
                            recpic_base64 = "data:img/jpg;base64," + Convert.ToBase64String(ms.ToArray());
                        }
                    }
                } else {
                    headimg = _friend_base64;
                    nickname = _friendUser.ShowName;
                }
            } catch (Exception e) {
                    WriteLog.Writelog("showreceivepic", e.ToString());
             }
          
            string str = @"
           <div style=""clear:both; width: 100%;"" >
           <li style=""  margin-bottom:13px;"" > <div style=""margin-top:6px;color:white; background:#808080; width:60px; border-radius:5px; position: absolute; right: 50%;text-align: center; "" class="" chat_nick"">" + msg.Time.ToString("T") + @"</div></li>  
           
           <div style=""width:40px; height:40px; border-radius:20px;border:2px solid #ADFF2F; overflow:hidden;float:left;"">
            <img  id = ""imgPre"" class=""chat_content_avatar"" src=""" + headimg + @""" style=""height: 40px; width: 40px;"">
           </div>
            <p style=""margin-left:50px; color:gray; "" class="" chat_nick"">" + nickname + @"</p>  
           <div style=""float:left;  top:5px; right:-16px;  width:0; height:0; font-size:0; border:solid 8px;  margin-top:-2px; border-color:#fff #e6e6fa #fff #fff; border-bottom-color:#fff;""></div>  
           <div onclick=""go();"" class= ""ss""  style=""float:left; border-radius:5px;  margin-top:-8px; padding: 10px; font-family:微软雅黑; margin-left:0px;height: auto; min-height:10px; width:auto; max-width:300px; background:#e6e6fa; ""><img src=""" + recpic_base64 + @""" /></div>    
           </div> ";   
            return str;
        }
        private string showreceivefilemsg( WXMsg msg ) {
            if (_meUser == null || _friendUser == null) {  return null;    }   
            string headimg = "";
            string nickname = "";
            if (msg.IsGroup) {
                nickname = msg.CrewNickName;
                try {
                    string picpath = path + "\\" + msg.CrewNickName.Trim() + ".jpg";
                    if (File.Exists(picpath)) {
                        using (MemoryStream ms = new MemoryStream()) {
                            Bitmap b = new Bitmap(picpath);
                            b.Save(ms, ImageFormat.Png);
                            _gro_base64 = "data:img/jpg;base64," + Convert.ToBase64String(ms.ToArray());
                        }
                        headimg = _gro_base64;
                    }
                    else {
                        headimg = _friend_base64;
                    }
                } catch (Exception e) {
                    WriteLog.Writelog("showreceivefilemsg", e.ToString());
                }
            }
            else {
                headimg = _friend_base64;
                nickname = _friendUser.ShowName;
            }

            using (MemoryStream ms = new MemoryStream()) {
                string picpath = msg.FileName;
                Bitmap backImage = new Bitmap(this.GetType(), "file.jpg");
                Bitmap b = new Bitmap(backImage);
                b.Save(ms, ImageFormat.Png);
                _fil_base64 = "data:img/jpg;base64," + Convert.ToBase64String(ms.ToArray());
            }
            string str = @"
           <div style=""clear:both; width: 100%;"" >
           <li style=""  margin-bottom:25px;"" > <div style=""margin-top:6px;color:white; background:#808080; width:60px; border-radius:5px; position: absolute; right: 50%;text-align: center; "" class="" chat_nick"">" + msg.Time.ToString("T") + @"</div></li>  
           <div style=""width:40px; height:40px; border-radius:20px;border:2px solid #ADFF2F; overflow:hidden;float:left;"">
                <img  id = ""imgPre"" class=""chat_content_avatar"" src=""" + headimg + @""" style=""height: 40px; width: 40px; "">
           </div>
           <p style=""margin-left:50px; color:gray; "" class="" chat_nick"">" + nickname + @"</p>  
           <div style=""float:left;  top:5px; right:-16px;  width:0; height:0; font-size:0; border:solid 8px;  margin-top:-2px; border-color:#fff #AAAAAA #fff #fff; border-bottom-color:#fff;""></div> 
           <div onclick=""go();""  class= ""ss"" style=""float:left; border-radius:5px; padding:10px;  margin-top:-10px; font-family:微软雅黑;height: 80px; min-height:10px; width:auto; background:white;border:1px solid #AAAAAA; "">                     
                    <div style=""width:140px;height:50px;text-overflow: ellipsis;overflow:hidden;margin-top:-10px; float:left;line-height:13px;"">
                       <p style=""text-overflow: ellipsis;overflow:hidden;font-size:14px;"">" + msg.FileName + @"</p>
                       <p style=""color:#AAAAAA;font-size:10px;"">" + msg.FileSize + "B" + @"</p>
                    </div>
                    <div style""width:140;float:right;"">
                       <img src=""" + _fil_base64 + @""" width =""30px"" />
                    </div>
                    <hr color=""#DDDDDD"" /> 
                    <p style=""margin:0px;font-size:10px;color:#AAAAAA;"">环球云控</p>    
           </div>
           </div> ";    
          
            return str;
        }
        private string showreceiveurlmsg( WXMsg msg ) {
            string _url_base64 = "data:img/jpg;base64,";
            string filena = null;
            if (_meUser == null || _friendUser == null) {
                return null;
            }
            string headimg = "";
            string nickname = "";
            if (msg.IsGroup) {
                nickname = msg.CrewNickName;
                try {
                    string picpath = path + "\\" + msg.CrewNickName.Trim() + ".jpg";  //群友头像
                    if (File.Exists(picpath)) {
                        using (MemoryStream ms = new MemoryStream()) {
                            Bitmap b = new Bitmap(picpath);
                            b.Save(ms, ImageFormat.Png);
                            _gro_base64 = "data:img/jpg;base64," + Convert.ToBase64String(ms.ToArray());
                        }
                        headimg = _gro_base64;
                    }
                    else {
                        headimg = _friend_base64;
                    }
                } catch (Exception e) {
                    WriteLog.Writelog("showreceiveurlmsg", e.ToString());
                }
            }
            else {
                headimg = _friend_base64;
                nickname = _friendUser.ShowName;
            }
            try {
                string picpath = path + @"\\" + msg.MsgId + "small.jpg";   //链接配图
                if (File.Exists(picpath)) {
                    filena = picpath;
                    using (MemoryStream ms = new MemoryStream()) {
                        Bitmap url = new Bitmap(filena);
                        url.Save(ms, ImageFormat.Png);
                        _url_base64 = "data:img/jpg;base64," + Convert.ToBase64String(ms.ToArray());
                    }
                }
            } catch (Exception e) {
                WriteLog.Writelog("showreceiveurlmsg", e.ToString());
            }
          
            string str = @"
           <div style=""clear:both; width: 100%;"" >
           <li style=""  margin-bottom:25px;"" > <div style=""margin-top:6px;color:white; background:#808080; width:60px; border-radius:5px; position: absolute; right: 50%;text-align: center; "" class="" chat_nick"">" + msg.Time.ToString("T") + @"</div></li>            
           <div style=""width:40px; height:40px; border-radius:20px;border:2px solid #ADFF2F; overflow:hidden;float:left;"">
                <img  id = ""imgPre"" class=""chat_content_avatar"" src=""" + headimg + @""" style=""height: 40px; width: 40px;"">
           </div>
           <p style=""margin-left:50px; color:gray; "" class="" chat_nick"">" + nickname + @"</p>  
           <div style=""float:left;  top:5px; right:-16px;  width:0; height:0; font-size:0; border:solid 8px;  margin-top:-2px; border-color:#fff #AAAAAA #fff #fff; border-bottom-color:#fff;""></div> 
           <div onclick=""go();""  class= ""ss"" style=""float:left; border-radius:5px;  margin-top:-10px;padding:10px; font-family:微软雅黑;height: 100px; min-height:10px; width:auto; background:white;border:1px solid #AAAAAA; "">                     
                    <div style=""width:180px;height:50px;text-overflow: ellipsis;overflow:hidden;margin-top:-15px"">
                       <p style=""text-overflow: ellipsis;overflow:hidden;font-size:14px;"">" + msg.FileName + @"</p>                       
                    </div>
                    <div style=""clear:both;"">
                        <div style=""width:140px;height:60px;text-overflow: ellipsis;overflow:hidden;margin-top:-10px; float:left;line-height:10px;"">
                            <p style=""color:#AAAAAA;font-size:10px;"">" + msg.FileName + @"</p>
                        </div>
                        <div style""width:140;float:right;"">
                            <img src=""" + _url_base64 + @""" width=""38px"" height=""38px"" />
                        </div>
                    </div> 
                   
           </div>
           </div>  "; 
     
            return str;
        }
        private string showreceiveverifymsg( WXMsg msg ) {
            if (_meUser == null || _friendUser == null) {
                return null;
            }
            string str = @" 
           <div style=""clear:both; width: 100%;"">
           <li style=""  margin-bottom:13px;"" > <div style=""margin-top:6px;color:white; background:#808080; width:60px; border-radius:5px; position: absolute; right: 50%;text-align: center; "" class="" chat_nick"">" + msg.Time.ToString("T") + @"</div></li>  
           
           <div style=""width:40px; height:40px; border-radius:20px;border:2px solid #ADFF2F; overflow:hidden;float:left;"">
            <img  id = ""imgPre"" class=""chat_content_avatar"" src=""" + _friend_base64 + @""" style=""height: 40px; width: 40px;"">
            </div>
           <p style=""margin-left:50px; color:gray; "" class="" chat_nick"">" + _friendUser.ShowName + @"</p>  
           <div style=""float:left;  top:5px; right:-16px;  width:0; height:0; font-size:0; border:solid 8px;  margin-top:-2px; border-color:#fff #AAAAAA #fff #fff; border-bottom-color:#fff;""></div> 
           <div onclick=""go();"" class= ""ss"" style=""float:left; border-radius:5px;  margin-top:-10px;padding:10px; font-family:微软雅黑;height: 100px; min-height:10px; width:auto; background:white;border:1px solid #AAAAAA; "">                     
                    <div style=""width:140px;height:40px;margin-top:-15px"">
                       <p style=""text-overflow: ellipsis;overflow:hidden;font-size:14px;"">" + msg.Msg + @"</p>                       
                    </div>
                    <div style=""clear:both;"">
                        <div style=""width:140px;height:60px;margin-top:-10px; float:left;line-height:10px;"">
                            <p style=""color:#AAAAAA;font-size:10px;text-overflow: ellipsis;overflow:hidden;white-space:nowrap;"">" + msg.V_Content + @"</p>
                        </div>
                        <div style""width:140;float:right;"">
                           <input type=""button"" value=""通过验证"" style=""color=#808080;""></input>
                        </div>
                    </div> 
                    <hr color=""#DDDDDD"" /> 
                    <p style=""margin:0px;font-size:10px;color:#AAAAAA;margin-top:-5px;"">环球云控</p>
           </div>
           </div> ";   
     
            return str;
        }    //名片
        private string showreceivecard( WXMsg msg ) { 
            if (msg == null || _friendUser == null) return string.Empty;
            string str = null;
            string tempName = null;
            string headimg = "";
            string nickname = "";
            if (msg.IsGroup) {
                nickname = msg.CrewNickName;
                try {
                    string picpath = path + "\\" + msg.CrewNickName.Trim() + ".jpg";
                    if (File.Exists(picpath)) {
                        using (MemoryStream ms = new MemoryStream()) {
                            Bitmap b = new Bitmap(picpath);
                            b.Save(ms, ImageFormat.Png);
                            _gro_base64 = "data:img/jpg;base64," + Convert.ToBase64String(ms.ToArray());
                        }
                        headimg = _gro_base64;
                    }
                    else {
                        headimg = _friend_base64;
                    }
                } catch (Exception e) {
                    WriteLog.Writelog("showreceivecard", e.ToString());
                }
            }
            else {
                headimg = _friend_base64;
                nickname = _friendUser.ShowName;
            }

            //名字长度取舍
            if (msg.Msg.Length > 10)
                tempName = msg.Msg.Substring(0, 10);
            else
                tempName = msg.Msg;

            //名片格式
            str = @"<script type=""text/javascript"">window.location.hash = ""#ok"";</script>
                            <div style=""clear:both;""><li style=""margin-bottom:13px; list-style:none;"">
                                <div style=""margin-top:6px; color:white; background:#808080; width:60px; border-radius:5px; position:absolute; right:50%; text-align:center;"">" + msg.Time.ToLongTimeString() + @"</div>
                            </li>
                            <br />
                            <div style=""clear:both; margin:15px 0 0 0;"">
                                <div style=""float:left;""><img style=""height:40px; width:40px; border-radius:40px; border:solid 2px #ADFF2F"" src = """ + headimg + @"""/></div>
                                <div onclick=""go();"" class=""ss"" style = ""border:1px solid Gray; height:100px; width:300px; float:left; margin:0 0 0 5px; border-radius:5px; cursor:pointer;"">
                                    <div style = ""height:20px; border-bottom:1px #33CC66 solid; padding:8px 5px 2px 5px; width:90%; margin:0 0 0 3%; text-align:left;"">名片</div>
                                    <div style=""height:70px; line-height:70px;"">
                                        <div style = ""float:left; margin:5px 0 5px 3%;""><img src = """ + msg.MsgId + @""" style=""border-radius:60px;"" height=""60"" width=""60""/></div>
                                        <div style = ""float:left; margin-left:10px;"">&nbsp;" + tempName + @"</div>
                                    </div>
                                </div>
                            </div>
                            </div></div>";
            return str;
        }
        private string showreceivevoice( WXMsg msg ) {
            if (_meUser == null || _friendUser == null) {
                return null;
            }
            string headimg = "";
            string nickname = "";
            if (msg.IsGroup) {
                nickname = msg.CrewNickName;
                try {
                    string picpath = path + "\\" + msg.CrewNickName + ".jpg";
                    if (File.Exists(picpath)) {
                        using (MemoryStream ms = new MemoryStream()) {
                            Bitmap b = new Bitmap(picpath);
                            b.Save(ms, ImageFormat.Png);
                            _gro_base64 = "data:img/jpg;base64," + Convert.ToBase64String(ms.ToArray());
                        }
                        headimg = _gro_base64;
                    }else {
                        headimg = _friend_base64;
                    }
                }
                catch (Exception e) {
                    WriteLog.Writelog("showreceivevoice", e.ToString());
                }
            }
            else {
                headimg = _friend_base64;
                nickname = _friendUser.ShowName;
            }

            using (MemoryStream ms = new MemoryStream()) {
                string picpath = msg.FileName;
                Bitmap backImage = new Bitmap(this.GetType(), "voice_left.png");
                Bitmap b = new Bitmap(backImage);
                b.Save(ms, ImageFormat.Png);
                _Voi_base64 = "data:img/jpg;base64," + Convert.ToBase64String(ms.ToArray());
            }
            string str = @"
           <script type=""text/javascript"">window.location.hash = ""#ok"";</script>
           <div style=""clear:both; width: 100%;"" >
           <li style=""  margin-bottom:25px;"" > <div style=""margin-top:6px;color:white; background:#808080; width:60px; border-radius:5px; position: absolute; right: 50%;text-align: center; "" class="" chat_nick"">" + msg.Time.ToString("T") + @"</div></li>  
           
           <div style=""width:40px; height:40px; border-radius:20px;border:2px solid #ADFF2F; overflow:hidden;float:left;"">
            <img  id = ""imgPre"" class=""chat_content_avatar"" src=""" + headimg + @""" style=""height: 40px; width: 40px;"">
           </div>
            <p style=""margin-left:50px; color:gray; "" class="" chat_nick"">" + nickname + @"</p>  
           <div style=""float:left;  top:5px; right:-16px;  width:0; height:0; font-size:0; border:solid 8px;  margin-top:-2px; border-color:#fff #e6e6fa #fff #fff; border-bottom-color:#fff;""></div>  
           <div onclick=""go();"" class= ""ss""  style=""float:left; border-radius:5px; padding-top: 10px; padding-left: 10px;  margin-top:-8px;  font-family:微软雅黑; margin-left:0px; height: 30px; width:60px; max-width:300px; background:#e6e6fa; ""><img src=""" + _Voi_base64 + @""" /></div>    
           </div>";   
        
           return  str;
        }
        #endregion

        /// <summary>
        /// 返回
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnBack_Click_1(object sender, EventArgs e) {
            Visible = false;
        }
        /// <summary>
        /// 查看详细信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnInfo_Click_1(object sender, EventArgs e) {
            if (FriendInfoView != null) {
                FriendInfoView(_friendUser);
            }
        }
        /// <summary>
        /// 表情
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        ///
        private void button1_Click_1(object sender, EventArgs e) {
            if (emojiPanel1.Visible == true) {
                emojiPanel1.Visible = false;
            }
            else {
                emojiPanel1.Visible = true;
            }           
        }

        private void richTextBox1_KeyDown(object sender, KeyEventArgs e) {
            if (e.KeyCode == Keys.Enter) {
                btn_send_Click(null, null);
                e.Handled = true;
            }
            //剪贴板粘贴发送文件事件
            if (e.Modifiers == Keys.Control && e.KeyCode == Keys.V) {
                IDataObject iData = Clipboard.GetDataObject();
                if (iData.GetDataPresent(DataFormats.FileDrop)) {
                    StringCollection s = Clipboard.GetFileDropList();
                    //遍历剪贴板中的文件集合
                    foreach (object f in s) {
                        string filePath = f.ToString();    //剪切板中的文件路径
                    }
                }
            }
            ////按下退格键
            //if (e.KeyCode == Keys.Back) {
            //    file_path = "";
            //    Clipboard.Clear();
            //}
        }
      
        private void WChatBox_Load_1(object sender, EventArgs e) {
            if (!Directory.Exists(path)) Directory.CreateDirectory(path);
            //设置属性 允许用户进行拖放操作
            richTextBox1.AllowDrop = true;
            //注册事件 
            richTextBox1.DragEnter += new DragEventHandler(richTextBox1_DragEnter);
            richTextBox1.DragDrop += new DragEventHandler(richTextBox1_DragDrop);

            webBrowser1.ScriptErrorsSuppressed = true;
            webBrowser1.IsWebBrowserContextMenuEnabled = false;
           // MessageBox.Show("520就快要到了！");
            webBrowser1.DocumentText = _baseHtml;
            if (WinXinBox._setting!=string.Empty) { Admin = sql.Select_child_Admin(WinXinBox._setting)[0]; }
            #region 截图注册热键
            uint ctrlHotKey = (uint)(KeyModifiers.Alt | KeyModifiers.Ctrl);
            // 注册热键为Alt+Ctrl+C, "100"为唯一标识热键
            HotKey.RegisterHotKey(Handle, 100, ctrlHotKey, Keys.C);
            #endregion  
        }

        #region 拖放文件发送事件
        private void richTextBox1_DragEnter( object sender, DragEventArgs e ) {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
                e.Effect = DragDropEffects.Link;
            else e.Effect = DragDropEffects.None;
        }
        string file_path = "";
        private void richTextBox1_DragDrop( object sender, DragEventArgs e ) {
            file_path = ((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString();
        }
        #endregion

        #region 截图程序
        private delegate void Rs(Rs r,string s);
        string savePath = string.Empty;
        private void btn_cutter_Click(object sender, EventArgs e) {
            savePath = path + "\\截图" + DateTime.Now.Ticks.ToString() + ".jpg";
            _SCREEN_CAPTURE.FrmCapture f = new _SCREEN_CAPTURE.FrmCapture();
            f.path = savePath;
            f.ShowDialog();


            IDataObject iData = Clipboard.GetDataObject();
            DataFormats.Format format = DataFormats.GetFormat(DataFormats.Bitmap);
            if (iData.GetDataPresent(DataFormats.Bitmap)) {
                richTextBox1.Paste(format);
                if (Clipboard.ContainsImage()) {
                    Image img = Clipboard.GetImage();
                    img.Save(savePath);
                    HaveScreenShot = true;
                }
                // Clipboard.Clear();
            }
            btn_cutter.Enabled = false;
            btn_cutter.Enabled = true;
        }

        private void GlobalKeyProcess() {
            this.WindowState = FormWindowState.Minimized;
            // 窗口最小化也需要一定时间
            Thread.Sleep(200);
            btn_cutter.PerformClick();
        }

        protected override void WndProc(ref Message m) {
            //如果m.Msg的值为0x0312那么表示用户按下了热键
            const int WM_HOTKEY = 0x0312;
            switch (m.Msg) {
            case WM_HOTKEY:
            if (m.WParam.ToString() == "100") {
                GlobalKeyProcess();
            }

            break;
            }

            // 将系统消息传递自父类的WndProc
            base.WndProc(ref m);
        }

        private void btn_cutter_MouseEnter(object sender, EventArgs e) {
            ToolTip p = new ToolTip();
            p.ShowAlways = true;
            p.SetToolTip(this.btn_cutter, "请点击截图按钮或者按组合键Ctrl+Alt+c");

        }

        private void WChatBox_Leave(object sender, EventArgs e) {
            // 卸载热键
            HotKey.UnregisterHotKey(Handle, 100);
        }

        #endregion
        /// <summary>
        /// 显示发送文件
        /// </summary>
        /// <param name="filename"></param>
        private void ShowSendFiles(string filename ) {
            FileInfo file = new FileInfo(filename);
            WXMsg msg = new WXMsg();
            string filetype = file.Extension.Split('.')[1].ToLower();
            string ful_nam = file.Name;
            if (filetype.Contains("ico") | filetype.Contains("gif") | filetype.Contains("xlsx") | filetype.Contains("pdf") | filetype.Contains("pptx") | filetype.Contains("docx") | filetype.Contains("jpg") | filetype.Contains("png") | filetype.Contains("bmp") | filetype.Contains("doc") | filetype.Contains("txt") | filetype.Contains("xls") | filetype.Contains("zip") | filetype.Contains("rar") | filetype.Contains("apk") | filetype.Contains("exe")) {
                switch (filetype) {
                case "jpg":
                msg.Type = "99";
                msg.Msg = "[图片]";
                msg.FileName = filename;
                break;

                case "png":
                msg.Type = "99";
                msg.Msg = "[图片]";
                msg.FileName = filename;
                break;

                case "bmp":
                msg.Type = "99";
                msg.Msg = "[图片]";
                msg.FileName = filename;
                break;

                case "gif":
                msg.Type = "99";
                msg.Msg = "[图片]";
                msg.FileName = filename;  //一种图片格式
                break;

                case "ico":
                msg.Type = "99";
                msg.Msg = "[图片]";
                msg.FileName = filename;  //一种图片格式ico
                break;

                case "txt":
                msg.Type = "49";
                msg.FileSize = file.Length.ToString();
                msg.Msg = ful_nam;
                msg.TxtUrl = "";
                msg.FileName = filename;
                break;
                case "doc":
                msg.TxtUrl = "";
                msg.Type = "49";
                msg.FileSize = file.Length.ToString();
                msg.Msg = ful_nam;
                msg.FileName = filename;
                break;

                case "xlsx":
                msg.TxtUrl = "";
                msg.Type = "49";
                msg.FileSize = file.Length.ToString();  //一种excel格式
                msg.Msg = ful_nam;
                msg.FileName = filename;
                break;

                case "pdf":
                msg.TxtUrl = "";
                msg.Type = "49";
                msg.FileSize = file.Length.ToString();  //一种pdf格式
                msg.Msg = ful_nam;
                msg.FileName = filename;
                break;

                case "pptx":
                msg.TxtUrl = "";
                msg.Type = "49";
                msg.FileSize = file.Length.ToString();   //一种ppt格式
                msg.Msg = ful_nam;
                msg.FileName = filename;
                break;

                case "docx":
                msg.TxtUrl = "";
                msg.Type = "49";
                msg.FileSize = file.Length.ToString();   //一种word格式
                msg.Msg = ful_nam;
                msg.FileName = filename;
                break;

                case "xls":
                msg.TxtUrl = "";
                msg.Type = "49";
                msg.FileSize = file.Length.ToString();
                msg.Msg = ful_nam;
                msg.FileName = filename;
           
                break;
                case "zip":
                msg.TxtUrl = "";
                msg.Type = "49";
                msg.Msg = ful_nam;
                msg.FileSize = file.Length.ToString();
                msg.FileName = filename;
          
                break;
                case "rar":
                msg.TxtUrl = "";
                msg.Type = "49";
                msg.Msg = ful_nam;
                msg.FileSize = file.Length.ToString();
                msg.FileName = filename;
           
                break;
                case "apk":
                msg.Type = "49";
                msg.TxtUrl = "";
                msg.Msg = ful_nam;
                msg.FileSize = file.Length.ToString();
                msg.FileName = filename;
           
                break;
                case "exe":
                msg.Type = "49";
                msg.TxtUrl = "";
                msg.Msg = ful_nam;
                msg.FileSize = file.Length.ToString();
                msg.FileName = filename;
         
                break;
                }

                msg.Readed = false;
                msg.Time = DateTime.Now;
                msg.IsReceive = 1;
                _friendUser_MsgSent(msg);
            }else {
              //  MessageBox.Show("不支持的文件格式");
            }
        }

        #region 快捷回复 按钮事件
        //删除快捷回复
        private void btn_delete_Click(object sender, EventArgs e) {
            if (checkedListBox1.CheckedItems.Count <= 0)
                return;
            List<string> l = new List<string>();
            foreach (var item in checkedListBox1.CheckedItems) {
                l.Add(item.ToString());
            }
            change_phone_info(l);
        }
        List<string> Lstr = new List<string>();
        /// <summary>
        /// 快捷回复
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_reply_Click_1( object sender, EventArgs e ) {
            string path = WChat.path.paths + "\\quick_reply.txt";
            if (panel1.Visible == true) {
                panel1.Visible = false;
            }
            else {
                #region 判断是否有此文件
                if (!File.Exists(path))
                    using (System.IO.FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write)) {
                        System.IO.StreamWriter sw = new StreamWriter(fs);
                        sw.Write("");
                        sw.Close();
                        fs.Close();
                    }
                #endregion

                #region 快捷回复

                //if (File.Exists(path) == false)  //如果不存在
                //{
                //    StreamWriter sw = new StreamWriter(path, true);  //创建
                //    sw.Write("快捷回复列表|");   //写入
                //    sw.Close();
                //    // checkedListBox1.Items.RemoveAt(0);
                //}
                //else
                //{
                //    checkedListBox1.Items.Clear();
                //    read_phone_info();
                //}

                #endregion
                SeachReply(path);
                panel1.Visible = true;
                Tbx_new_reply_LostFocus(tbx_new_reply, null);
            }
        }
        private void btn_reply_MouseEnter(object sender, EventArgs e) {
            ToolTip p = new ToolTip();
            p.ShowAlways = true;
            p.SetToolTip(this.tbx_new_reply, "快捷回复");
        }

        //双击事件
        private void checkedListBox1_MouseDoubleClick(object sender, MouseEventArgs e) {
            if (checkedListBox1.Items.Count != 0) {
                richTextBox1.AppendText(checkedListBox1.Items[checkedListBox1.SelectedIndex].ToString());
                panel1.Visible = false;
            }
        }

        #region 读取本地存储回复信息
        void SeachReply( string p ) {
            Lstr = null;
            checkedListBox1.Items.Clear();
            using (System.IO.StreamReader read = new StreamReader(p)) {
                string s = read.ReadToEnd();
                Lstr = (s.Split('\n')).ToList();
                read.Close();
                foreach (string item in Lstr) {
                    if (item == "")
                        continue;
                    checkedListBox1.Items.Add(item);
                }
            }
        }
        #endregion

        //新建快捷回复
        private void btn_new_reply_Click(object sender, EventArgs e) {
            string text = tbx_new_reply.Text.Trim();
            if (text != "" && !Lstr.Contains(text)) {
                string path = WChat.path.paths + "\\quick_reply.txt";
                using (System.IO.StreamWriter sw = new StreamWriter(path, true)) {
                    sw.WriteLine(text);
                    sw.Close();
                }
                checkedListBox1.Items.Add(text);
                SeachReply(path);
                tbx_new_reply.Text = "";
            }
            else
                MessageBox.Show("已有此内容");
        }

        //修改
        private void change_phone_info( List<string> Lstring ) {
            string path = WChat.path.paths + "\\quick_reply.txt";

            if (!File.Exists(path) || Lstr == null)//如果不存在文件
                return;
            StringBuilder sb = new StringBuilder();
            foreach (string item in Lstring) {
                Lstr.Remove(item);
                checkedListBox1.Items.Remove(item);
            }
            foreach (string item in Lstr) {
                if (item != "")
                    sb.Append(item + "\n");
            }
            using (System.IO.FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write)) {
                System.IO.StreamWriter sw = new StreamWriter(fs);
                sw.Write(sb.ToString());
                sw.Close();
                sw.Dispose();
                fs.Close();
            }
        }
        

        #endregion

        private void panel1_Click(object sender, EventArgs e) {
            panel1.Visible = false;
        }

        private void plTop_Resize(object sender, EventArgs e) {
            lblInfo.Location = new Point((plTop.Width - lblInfo.Width) / 2, lblInfo.Location.Y);
        }

        /// <summary>
        /// 加载更多！
        /// </summary>
        public void LoadMore() {
            // MessageBox.Show("加载更多！");
            Thread getchlo = new Thread(ShowFirstMsg);
            getchlo.Start();
        }
        string chlo_tim = "";
        /// <summary>
        /// 消息点击事件
        /// </summary>
        /// <param name="message"></param>
        public void getContext(string message) {
           // MessageBox.Show("当前消息的索引为：" + message);
            int index = int.Parse(message);

            if(piczoom[index].Type == "42") {       //名片
                string path = WChat.path.paths + "\\" + WXUser.RemoveHtml(piczoom[index].Msg) + "big.jpg";
                Card c = new Card();
                c.Location = new Point(MousePosition.X, MousePosition.Y);
                c.w = piczoom[index];
                c.meUser = _meUser;
                c.savePathName = path;
                c.ShowDialog();
            }
            // MessageBox.Show("数组中的数据：" + piczoom[index].Msg+"数据总数："+ piczoom.Count.ToString());
            if (piczoom[index].Type =="49") {    //文件或者链接
                //MessageBox.Show(piczoom[index].Type+","+piczoom[index].TxtUrl);
                if (piczoom[index].TxtUrl.Length != 0) {
                    hqbrower _brower = new hqbrower();
                    _brower.openwebpage(piczoom[index].TxtUrl);
                    _brower.Show();
                }
                else {   //文件
                    string filepath = WChat.path.paths;
                    string filename = filepath + "\\" + piczoom[index].FileName;
                    if (File.Exists(filepath+filename)) {
                        System.Diagnostics.Process.Start("explorer.exe", filepath);
                    }
                    else {
                        DowloadFile df = new DowloadFile();
                        df.user = _friendUser;
                        df.from_user_name = _friendUser; //值
                        df.mediaid = piczoom[index].MediaId;       //值
                        df.filenam = piczoom[index].FileName;     //值

                        Thread thread = new Thread(new ThreadStart(df.downloadfiles));
                        thread.IsBackground = true;
                        thread.Start();
                        System.Diagnostics.Process.Start("explorer.exe", filepath);
                    }                                    
                }
            }
           
            if (piczoom[index].Type =="3") {  //为图片
                
                string picpath = WChat.path.paths +"\\"+ piczoom[index].MsgId + ".jpg";
                if (File.Exists(picpath)) {
                    picbox pic = new picbox();
                    pic.showpic(picpath);
                    pic.Show();
                }
                else {
                    _friendUser.SavePic();
                    if (File.Exists(picpath)) {
                        picbox pic = new picbox();
                        pic.showpic(picpath);
                        pic.Show();
                    }

                }
            }else if(piczoom[index].Type == "37") {
                _friendUser.verify_usr(piczoom[index].V_Value, piczoom[index].V_UserTicket);
            }else if (piczoom[index].Type == "99") {
                try {
                    if (File.Exists(piczoom[index].FileName)) {
                        picbox pic = new picbox();
                        pic.showpic(piczoom[index].FileName);
                        pic.Show();
                    }
                } catch { }
            }else if(piczoom[index].Type == "34") {     //语音消息
                string voicepath = WChat.path.paths + "\\" + piczoom[index].MsgId + ".mp3";
                if (File.Exists(voicepath)) {
                    BSoundPlayer bp = new BSoundPlayer();
                    bp.FileName = voicepath;
                    bp.Play();
                }
            }

            chlo_tim = piczoom[index].Time.ToString();
        }

        #region 聊天窗口右键菜单
        string str = "";
        WXMsg wRightMenu = new WXMsg();                                 //右键菜单专用类
        public void getRight( string message )                                  //聊天窗口右键菜单
        {
            str = message;
            if (str != "") {
                path = WChat.path.paths;
                int index = int.Parse(message);
                wRightMenu = piczoom[index];
                brower_righ_menu.Show(new Point(MousePosition.X + 3, MousePosition.Y));
            }
        }
        #endregion

        /// <summary>
        /// 点击发送文字或截图
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_send_Click(object sender, EventArgs e)
        {
            if (file_path!="") {
                DowloadFile df = new DowloadFile();
                df.user = _friendUser;
                df.from_user_name = _meUser; //值
                df.to = _friendUser;       //值
                df.filenam = file_path;     //值
                ShowSendFiles(file_path);
                Thread thread = new Thread(new ThreadStart(df.uploadfiles));
                thread.IsBackground = true;
                thread.Start();
                //将路径清空
                file_path = "";
                //将消息框清空
                richTextBox1.Text = "";
            }
            else if (richTextBox1.Text != null && _friendUser != null && _meUser != null)
            {
                if (richTextBox1.Text.Trim() != string.Empty)
                {
                    WXMsg send_msg = new WXMsg();//放到全局，配合线程试用
                    send_msg.From = _meUser.UserName;
                    send_msg.Msg = FindSinsitive(richTextBox1.Text);  //完美很关键的一句
                    send_msg.Fr_NickName = _meUser.NickName;
                    send_msg.To_NickName = _friendUser.NickName;
                    send_msg.IsReceive = 1;
                    send_msg.Readed = false;
                    send_msg.To = _friendUser.UserName;
                    send_msg.Type = "1";
                    send_msg.Time = DateTime.Now;
                    Quan_msg = send_msg;
                    _friendUser_MsgSent(send_msg);
                    _friendUser.InsertChatLog(_meUser.NickName, send_msg);
                    Thread sendmsg = new Thread(SendMsgs);
                    sendmsg.Start();
                }
                Sendpic();
                richTextBox1.Text = "";
                //Clipboard.Clear();
            }   
        }
        /// <summary>
        /// 关键词处理
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        private string FindSinsitive(string content ) {
            string sensitive = string.Empty; ;
            bool have_sensitive = false;
            List<string> sensiList = new List<string>();
            if (content!=string.Empty && Admin != string.Empty) {
                sensiList = sql.GetSensitive(Admin);
                if (sensiList!=null) {
                    for (int i = 0; i < sensiList.Count; i++) {
                        if (content.Contains(sensiList[i].Trim())) {
                            have_sensitive = true;
                            sensitive = content.Replace(sensiList[i].Trim(), "****");
                        }
                    }
                    if (!have_sensitive) {
                        have_sensitive = false;
                        return content;
                    }
                } 
                return sensitive;
            }
            return content;
        }
        /// <summary>
        /// 发送文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_sendfile_Click( object sender, EventArgs e ) {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Title = "选择要发送的文件或图片";
            if (DialogResult.OK == dlg.ShowDialog()) {
                DowloadFile df = new DowloadFile();
                df.user = _friendUser;
                df.from_user_name = _meUser; //值
                df.to = _friendUser;       //值
                df.filenam = dlg.FileName;     //值
                ShowSendFiles(dlg.FileName);
                Thread thread = new Thread(new ThreadStart(df.uploadfiles));
                thread.IsBackground = true;
                thread.Start();
            }
        }

        #region 发送方法
        //发送消息方法
        private void SendMsgs(){
            _friendUser.SendMsgToServer(Quan_msg);
        }
        //发送图片方法
        private void Sendpic()
        {
            try
            {
                if (Clipboard.ContainsImage()) {
                    //如果复制了图片
                    if (sendpath != "") {
                        ShowSendFiles(sendpath);
                        _friendUser.SendFiles(_meUser, _friendUser, sendpath);
                    }
                    else { //如果刚刚截图了（粘贴版有图片）
                        ShowSendFiles(savePath);
                        _friendUser.SendFiles(_meUser, _friendUser, savePath);
                    }
                }
                else if (Clipboard.ContainsFileDropList()) {//如果复制了文件
                    if (Files) {
                        ShowSendFiles(sendpath);
                        _friendUser.SendFiles(_meUser, _friendUser, sendpath);
                    }
                    else if (sendpath == "" && savePath == "") {
                        //既没截图有没在软件里复制信息
                        string pa = (Clipboard.GetData(DataFormats.FileDrop) as string[])[0];
                        //MessageBox.Show(pa);
                        ShowSendFiles(pa);
                        _friendUser.SendFiles(_meUser, _friendUser, pa);
                    }
                }
                if (Files)
                    Files = false;
                sendpath = "";
                savePath = "";
            }
            catch (Exception)
            {
            }
        }
        #endregion

        private void btnClose_Click(object sender, EventArgs e) {
            panel1.Visible = false;
        }
        private void 删除该条消息ToolStripMenuItem_Click(object sender, EventArgs e) {
            try {
                if (chlo_tim != "") {
                    ss.DeleteChatLog(_meUser.Myuin, chlo_tim);
                    Clear();    //清空界面
                    chlo_tim = "";
                    ShowFirstMsg(); 
                }  
            } catch { }
           
        }
        public void Clear() {
            _totalHtml = "";
            webBrowser1.DocumentText = "";
        }

        #region 快捷回复图片
        //快捷回复图片按钮事件
        private void btn_pic_reply_Click( object sender, EventArgs e ) {
            read_info();
            if (panel2.Visible == false && flowLayoutPanel1.Visible == false) {
                panel2.Visible = true;
                flowLayoutPanel1.Visible = true;
            }
            else {
                panel2.Visible = false;
                flowLayoutPanel1.Visible = false;
            }
        }
       
        //添加图片按钮事件
        private void btn_add_img_Click( object sender, EventArgs e ) {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Title = "选择要发送的图片";
            dlg.Filter = "Image files (*.JPG;*.JPEG;*.BMP;*.GIF;*.PNG)|*.jpg*.jpeg;*.gif;*.bmp|AllFiles (*.*)|*.*";

            if (dlg.ShowDialog() == DialogResult.OK) {
                //获取图片路径
                string photopath = dlg.FileName.ToString();
                //获取图片名称
                string filename = Path.GetFileName(photopath);
                //创建文件夹（如果有 则不创建）
                System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(@"D:\Documents\HuanQiuYunKong\Quick_Img");
                di.Create();
                //将图片复制到指定文件夹
                FileInfo f = new FileInfo(photopath);
                string NewImg = @"D:\Documents\HuanQiuYunKong\Quick_Img\" + filename;
                f.CopyTo(NewImg, true);
                //将图片路径保存至配置文件
                write_info(NewImg);
                //刷新图片
                read_info();
            }
        }
        //创建配置文件
        private void write_info( string str ) {
            try {
                string path = System.Environment.CurrentDirectory + "\\Quick_Img.txt";
                StreamWriter sw = new StreamWriter(path, true);

                sw.Write(str + "|");  //写入
                sw.Close();
                sw.Dispose();
            }
            catch { }
        }
        //读取配置文件
        private void read_info() {
            flowLayoutPanel1.Controls.Clear();
            string str = "";
            string path = System.Environment.CurrentDirectory + "\\Quick_Img.txt";
            //如果没有配置文件不执行
            if (!File.Exists(path))
                return;
            StreamReader sr = new StreamReader(path, false);
            //编码格式（整治乱码） UnicodeEncoding.GetEncoding("GB2312")
            FileInfo fi = new FileInfo(path);
            if (fi.Length != 0) {
                str = sr.ReadLine().ToString();
                sr.Close();
                Regex.Replace(str, @"\s+", "/r/n");
                string[] sArray = str.Split('|').Distinct().ToArray();
                for (int i = 0; i < sArray.Length; i++) {
                    if (sArray[i].ToString() != "") {
                        PictureBox picb = new PictureBox();
                        picb.Width = 100;
                        picb.Height = 100;
                        picb.Name = "pictureBox" + i.ToString();
                        picb.Click += One_Click;
                        picb.DoubleClick += Img_DoubleClick;
                        picb.Tag = sArray[i];
                        picb.SizeMode = PictureBoxSizeMode.StretchImage;
                        Image img = Image.FromFile(sArray[i]);
                        Image bmp = new Bitmap(img);
                        picb.Image = bmp;
                        flowLayoutPanel1.Controls.Add(picb);
                        img.Dispose();
                    }
                }
                sr.Dispose();
            }
        }
        //双击图片 进行发送
        private void Img_DoubleClick( object sender, EventArgs e ) {
            PictureBox p = sender as PictureBox;
            string str_url = p.Tag.ToString();
            panel2.Visible = false;
            flowLayoutPanel1.Visible = false;

            DowloadFile df = new DowloadFile();
            df.user = _friendUser;
            df.from_user_name = _meUser; //值
            df.to = _friendUser;       //值
            df.filenam = str_url;     //值
            ShowSendFiles(str_url);
            Thread thread = new Thread(new ThreadStart(df.uploadfiles));
            thread.IsBackground = true;
            thread.Start();
  
        }
        //单击选中
        string url;
        private void One_Click( object sender, EventArgs e ) {
            PictureBox p = sender as PictureBox;
            p.Width = 105;
            p.Height = 105;
            url = p.Tag.ToString();
        }

        private void btn_del_img_Click( object sender, EventArgs e ) {
            change_info();
            if (File.Exists(url)) {
                File.Delete(url);
            }
            read_info();
        }

        //删除指定快捷图片
        private void change_info() {
            string str = "";
            string path = System.Environment.CurrentDirectory + "\\Quick_Img.txt";
            if (File.Exists(path) == false)//如果不存在文件
            {
                MessageBox.Show("读取配置文件失败！");
            }
            else {
                StreamReader sr = new StreamReader(path, false);
                //编码格式（整治乱码） UnicodeEncoding.GetEncoding("GB2312")
                FileInfo fi = new FileInfo(path);
                if (fi.Length != 0) {
                    str = sr.ReadLine().ToString();
                    sr.Close();
                    System.IO.File.WriteAllText(path, string.Empty);
                    Regex.Replace(str, @"\s+", "/r/n");
                    string[] sArray = str.Split('|');
                    List<string> arr = new List<string> { };
                    //for循环遍历 
                    for (int i = 0; i < sArray.Length; i++) {
                        if (sArray[i] != url) {
                            arr.Add(sArray[i]);
                        }
                    }
                    //写入配置文件
                    StreamWriter sw = new StreamWriter(path, true);
                    for (int i = 0; i < arr.Count; i++) {
                        if (arr[i].ToString() != "") {
                            sw.Write(arr[i] + "|");
                        }
                    }
                    sw.Close();
                    sw.Dispose();
                }
                sr.Dispose();
            }
        }
        #endregion

        private void lblInfo_Click( object sender, EventArgs e ) {
            FriendDetails fd = new FriendDetails();
            fd.GetExtra(_friendUser, _meUser);
            fd.Show();

        }

        private void 粘贴ToolStripMenuItem_Click( object sender, EventArgs e ) {
            richTextBox1.Paste();
        }
        #region 右键菜单（复制）
        bool Files = false;
        string sendpath = "";
        private void 复制ToolStripMenuItem_Click_1( object sender, EventArgs e ) {
            Clipboard.Clear();
            if (HaveScreenShot)
                HaveScreenShot = false;
            //MessageBox.Show(wRightMenu.Type);
            if (wRightMenu.Type == "49" && wRightMenu.TxtUrl == "")                                     //文件
            {
                if (wRightMenu.FileName != "微信转账") {
                    StringCollection sc = new StringCollection();
                    sc.Add(wRightMenu.FileName);
                    sendpath = WChat.path.paths + "\\" + wRightMenu.FileName;
                    MessageBox.Show(sendpath);
                    Clipboard.SetFileDropList(sc);
                    Files = true;
                }
                else {
                    if (wRightMenu.FileName != "微信转账")                                                          //网址
                        Clipboard.SetText(wRightMenu.TxtUrl);
                }
            }
            else if (wRightMenu.Type == "1")                                                                          //消息
                Clipboard.SetText(wRightMenu.Msg);
            else if (wRightMenu.Type == "3")                                                                          //图片
            {
                sendpath = WChat.path.paths + "\\" + wRightMenu.MsgId + ".jpg";
                //MessageBox.Show(sendpath);
                Image img = Image.FromFile(sendpath);
                Clipboard.SetImage(img);
            }
            else if (wRightMenu.Type == "99")                                                                        //图片
            {
                sendpath = wRightMenu.FileName;
                //MessageBox.Show(sendpath);
                Image img = Image.FromFile(sendpath);
                Clipboard.SetImage(img);
            }
        }
        #endregion

        #region txt话术导入
        private void button2_Click( object sender, EventArgs e ) {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "(*.txt)|*.txt";
            ofd.ShowDialog();
            string p = ofd.FileName;
            if (p != "") {
                string path = WChat.path.paths + "\\quick_reply.txt";
                string strs = "";

                using (FileStream fst = new FileStream(p, FileMode.Open)) {
                    StreamReader sr = new StreamReader(fst, Encoding.GetEncoding("GB2312"));
                    strs = sr.ReadToEnd();
                    sr.Close();
                } 
             
                using (System.IO.FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.Write)) {
                    System.IO.StreamWriter sw = new StreamWriter(fs);
                    sw.WriteLine(strs);
                    sw.Close();
                    sw.Dispose();
                    fs.Close();
                }
                SeachReply(path);
            }
        }
        #endregion

    }
}
